2

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.

  1. Must this file (class Main) with the object scheduler be running in order for the program in the file to be executed every minute?
  2. Or once I run this once will the scheduler pass off this job to the operating system?
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216

1 Answers1

3

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.

jbx
  • 21,365
  • 18
  • 90
  • 144
  • What is the most efficient method in cron4j to run a task everyday? I would have to make the Main thread sleep forever? – CodeKingPlusPlus Nov 18 '12 at 04:16
  • What benefits would Quartz give me? The only necessity I have is to run the same program with different arguments once or twice everyday. – CodeKingPlusPlus Nov 18 '12 at 04:24
  • I wouldn't go for a Java based solution then. Go for an OS based solution, i.e. crontab on Linux or Windows task scheduler on Windows. Quartz is just more advanced and more mature, so most industry grade application servers come with it integrated. – jbx Nov 18 '12 at 13:46