3

I'm writing a Java-based shell-type... erm.. thing. Anyway, one of the commands I am implementing is a schedule command, where you can tell it the time you want to run the command and it waits for the time, runs the command once, and exits. However, I can't figure out how to get it to check the time - I implemented one that just checks if the dates are equal, did a little research to see if a better solution existed, then found that apparently Date is not a good thing to use. What should I do?

MCVE:

import java.util.Date;

public class Scheduler extends Thread {
    private Date goAt;
    private String command;
    public Scheduler(Date goAt, String command) {
        this.goAt = goAt;
        this.command = command;
    }
    public void start() {
        super.start();
    }
    public void run() {
        while (!goAt.equals(new Date())) {} //Wait until the dates are equal
        runCommand(command); //In the real thing, this runs the command.
    }
    public void runCommand(String command) {
        System.out.println("Command: " + command);
    }
    public static void main(String[] args) {
        Scheduler task = new Scheduler(new Date(System.currentTimeMillis() + 5000));
        task.start();
    }
}

I would like this to be done without using third-party libraries, or libraries that must be downloaded separately. If there is no way to do so, then I will accept answers with a third-party library, but preference goes to solutions without them. Also ideal would be if answers allowed me to directly specify a time to run the command, rather than calculating the relative time difference and using that.

Nic
  • 6,211
  • 10
  • 46
  • 69

2 Answers2

2

Use the builtin java.util.Timer class to schedule code to run at a given future time or after a given delay.

matt b
  • 138,234
  • 66
  • 282
  • 345
0

One option is to use Timers/TimerTasks to schedule commands - here is a tutorial.

Another option is to put the commands in a DelayQueue (with the delay set to the time that the task should fire), then use a consumer thread to repeatedly call take on the queue and fire the commands it removes.

In terms of third party libraries, Quartz is a good scheduler.

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • Timers can get the job done but they have issues to watch out for. It's recommended to use http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html instead. See http://stackoverflow.com/questions/409932/java-timer-vs-executorservice for the explanation. – Tansir1 May 09 '13 at 17:34
  • Dead link for the primary part of the answer. Please provide example code in the answer. – Matt Clark Oct 02 '16 at 14:06