I want to execute a few lines of program after a certain amount of seconds. How does one do this?
I already tried something but it won't work. The lamps are supposed to go on and off after a certain amount of seconds.
Beginner program so sorry if this is a stupid question.
package io.github.zeroone3010.yahueapi;
import org.omg.PortableServer.POAManagerPackage.State;
import java.util.*;
public class looptest
{
public static void main(String args[])
{
final String bridgeIp = "ip";
final String apiKey = "key";
final Hue hue = new Hue(bridgeIp, apiKey);
final Room room = hue.getRoomByName("Woonkamer").get();
int counter = 0;
boolean loop;
Timer timer = new Timer();
new java.util.Timer().schedule(
new java.util.TimerTask()
{
int secondsPassed = 0 ;
public void run()
{
secondsPassed++;
System.out.println(secondsPassed);
room.getLightByName("Tv 1").get().turnOn();
if (secondsPassed > 3) // after 3 seconds tv 2 on
room.getLightByName("Tv 2").get().turnOn();
if (secondsPassed > 11) // after 11 seconds tv 1 and 2 off
room.getLightByName("Tv 1").get().turnOff();
room.getLightByName("Tv 2").get().turnOff();
}
},
5000
};
{
I understand that your intention is to:
You should turn the "Tv 1" on light in the main method (outside of Timer.schedule block). Moreover you should schedule both future activities as independent tasks with proper delays as follows:
room.getLightByName("Tv 1").get().turnOn();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
room.getLightByName("Tv 2").get().turnOn();
}
}, 3000L);
timer.schedule(new TimerTask() {
@Override
public void run() {
room.getLightByName("Tv 1").get().turnOff();
room.getLightByName("Tv 2").get().turnOff();
}
}, 11000L);
I hope it helps.