I am using the cron4j library for scheduling a program. Here is my code:
public class Main {
public static void main(String[] args) {
// Declares the file.
File file = new File("cron4j.txt");
// Creates the scheduler.
Scheduler scheduler = new Scheduler();
// Schedules the file.
scheduler.scheduleFile(file);
// Starts the scheduler.
scheduler.start();
// Stays alive for five minutes.
try {
Thread.sleep(5L * 60L * 1000L);
} catch (InterruptedException e) {
;
}
// Stops the scheduler.
scheduler.stop();
}
}
Inside the “cron4j.txt” file I have set my program to run every minute.
- Must this file (class Main) with the object scheduler be running in order for the program in the file to be executed every minute?
- Or once I run this once will the scheduler pass off this job to the operating system?
The program must be continuously running. Cron4j is just hiding the scheduling for you but in reality is a bunch of threads sleeping and waiting for the time to come for execution. The operating system just sees your program as a normal one continuously running.
In order to use the operating system’s scheduling mechanisms, you do not use Cron4j but use crontab (on linux) or the task scheduler on Windows.
One more sophisticated scheduler for Java, which is more considered the Industry standard is Quartz Scheduler. However the concept is the same, your program needs to be running for the scheduled tasks to happen.