User avatar
addeswe
Posts: 22
Joined: Fri Jul 19, 2013 3:49 pm
Location: Sweden

Background task, Async?

Thu Jul 13, 2017 8:40 am

First of, I'm pretty new with Java. So this will be a stupid question most likely. However... My parents live where there is a lot of thunder. And they need a good way to shut down the pi without logging into the pi itself. So my idea was to write an application. And this is what I would want.

Code: Select all

Application --[GPIO reader (pi4j)]
                   |-[blinking led]
I can write all the code. But if it would be Android. I guess the proper way would be to send the led-function to a AsyncTask. So it runs in the background as long as the program is runnig. That way, they know when it's halted and pull the plug. Is there a way to do this background task in Java (without Android). The reading of GPIO would be blocking the other thread afaik.

Thanks in advance.
A
The best thing about UDP jokes is that I don't care if you get it or not!
“Knock, knock.” - “Who’s there?” - very long pause…. - “Java.”

mattlewis
Posts: 104
Joined: Sat Jan 12, 2013 3:05 pm
Location: UK
Contact: Website

Re: Background task, Async?

Sun Jul 16, 2017 6:12 pm

This is what I would do with diozero:

Code: Select all

import java.util.concurrent.TimeUnit;

import com.diozero.devices.Button;
import com.diozero.devices.LED;
import com.diozero.util.DioZeroScheduler;

public class Listener {
	public static void main(String[] args) {
		try (Button button = new Button(16); LED led = new LED(22)) {
			// Toggle the LED every second
			DioZeroScheduler.getNonDaemonInstance().scheduleAtFixedRate(() -> led.toggle(), 0, 1, TimeUnit.SECONDS);
			
			// Do something whenever the button is pressed
			button.whenPressed(() -> {
				System.out.println("Pressed");
			});
		}
	}
}
Matt
http://www.diozero.com/

User avatar
addeswe
Posts: 22
Joined: Fri Jul 19, 2013 3:49 pm
Location: Sweden

Re: Background task, Async?

Mon Jul 17, 2017 6:24 am

Thanks for the reply. However I've come to the conclusion to run the led in a threaded task. :-)
The best thing about UDP jokes is that I don't care if you get it or not!
“Knock, knock.” - “Who’s there?” - very long pause…. - “Java.”

User avatar
savageautomate
Posts: 225
Joined: Thu Aug 16, 2012 3:20 pm
Location: USA
Contact: Website

Re: Background task, Async?

Sun Aug 06, 2017 6:18 pm

I think you have already solved this for your needs but here is another option using Pi4J:

This example shows how to configure a GPIO pin to blink as a background task.
https://github.com/Pi4J/pi4j/blob/maste ... ample.java

Technically speaking its running in a worker thread via the shared ExecutorService within Pi4J.
Robert Savage | Follow me @savageautomate
http://www.pi4j.com | http://www.pislices.com
http://www.savagehomeautomation.com

Return to “Java”

Who is online

Users browsing this forum: No registered users and 4 guests