There are several ways to solve this problem, considering a 100% back end system.
Use the System Scheduler
Windows has a very flexible and powerful Task Scheduler. It may be simpler to configure it to call your program via the command line at scheduled times.
Using the Java Scheduler
If you want to do the same Java scheduling, use an API class that already does this for you. You do not need milliseconds, seconds, minutes, and hours.
See, for example, the documentation for ScheduledExecutorService
. There is everything and even a functional example, which I adapted in the code below:
public class BeeperControl {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
//beep task
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
//beep each hour
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 0, 1, TimeUnit.HOURS);
//cancel beep task
final Runnable canceler = new Runnable() {
public void run() {
beeperHandle.cancel(false);
}
};
//stop beep after 1 day
scheduler.schedule(canceler, 1, TimeUnit.DAYS);
}
public static void main(String[] args) {
new BeeperControl().beepForAnHour();
}
}
Let's look at the above code:
The ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1)
line calls a factory method to create a scheduled services performer .
Within the beepForAnHour
method, the first block declares an implementation of Runnable
called beeper
. This is the same API that implements threads . This specifically prints beep
on the console.
The scheduler.scheduleAtFixedRate(beeper, 0, 1, TimeUnit.HOURS)
command is the most interesting here. It schedules the execution of our beeper ) at regular intervals of one hour (parameters 3 and 4), with the first execution being immediate (second parameter).
The following excerpt creates another Runnable
called canceler
. This will be responsible, when executed, for canceling the periodic schedule previously made.
The scheduler.schedule(canceler, 1, TimeUnit.DAYS);
command schedules a single execution of our canceler
to exactly one day later. Then the next day, beep
will stop.
Critical scenario
In case of scheduled tasks that are critical to the business, it is interesting to replicate the program on multiple servers. If one of them fails, the others will be able to perform the critical routine. However, if the processing is heavy, it is not convenient for it to run redundantly, that is, it runs multiple times on those different servers.
For such cases, there are scheduling libraries like Quartz that have specific settings for clusters of servers . That way, you can deploy the application to multiple servers, and in this example, Quartz will manage the execution, ensuring that your job runs properly once.
Even with a single server, Quartz can ensure that a runtime lost when the server is in service will resume as soon as the server is available.