Page 1 of 1

Background task, Async?

Posted: Thu Jul 13, 2017 8:40 am
by addeswe
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.

Re: Background task, Async?

Posted: Sun Jul 16, 2017 6:12 pm
by mattlewis
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(() -> {

Re: Background task, Async?

Posted: Mon Jul 17, 2017 6:24 am
by addeswe
Thanks for the reply. However I've come to the conclusion to run the led in a threaded task. :-)

Re: Background task, Async?

Posted: Sun Aug 06, 2017 6:18 pm
by savageautomate
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. ...

Technically speaking its running in a worker thread via the shared ExecutorService within Pi4J.