Search code examples
javatimer

Execute a few lines of program after a certain amount of seconds


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
    };          
    {

Solution

  • I understand that your intention is to:

    • turn "Tv 1" light on immediately
    • turn "Tv 2" light on after 3 seconds
    • turn "Tv 1" and "Tv 2" lights off after 11 seconds

    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.