42

I'm writing a standalone batch Java application to read data from YouTube. I want to set up an cron job to do certain job every hour.

I search and found ways to do a cron job for basic operations but not for a Java application.

nobody
  • 19,814
  • 17
  • 56
  • 77
user3138111
  • 561
  • 1
  • 6
  • 10
  • 1
    Are you asking literally for how to work with Unix cron? If you just want a way to make your Java app work periodically, see the [`ScheduledExecutorService`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html). This built-in Java class will run a given [`Runnable`](http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html) as often as you specify. This approach is contained within Java with no need for external utilities like `cron`. – Basil Bourque Mar 05 '14 at 07:33
  • find this.. https://stackoverflow.com/questions/44270994/how-make-a-job-to-determinate-date-only-once-from-java – marlonpya May 30 '17 at 23:32

3 Answers3

61

You can use TimerTask for Cronjobs.

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);
   }

}

MyTask.java

class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
     System.out.println("Hi see you after 10 seconds");
   }

}

Alternative You can also use ScheduledExecutorService.

Indrajith
  • 880
  • 12
  • 21
  • Another alternative is [JobRunr](http://github.com/jobrunr/jobrunr): it allows to run [CRON jobs](https://www.jobrunr.io/en/documentation/background-methods/recurring-jobs/) using a annotation if you are using Spring Framework or Micronaut: `@Recurring(id = "my-recurring-job", cron = "*/5 * * * *")` – rdehuyss Apr 26 '22 at 06:43
10

First I would recommend you always refer docs before you start a new thing.

We have SchedulerFactory which schedules Job based on the Cron Expression given to it.

    //Create instance of factory
    SchedulerFactory schedulerFactory=new StdSchedulerFactory();

    //Get schedular
    Scheduler scheduler= schedulerFactory.getScheduler();

    //Create JobDetail object specifying which Job you want to execute
    JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);

    //Associate Trigger to the Job
    CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");

    //Pass JobDetail and trigger dependencies to schedular
    scheduler.scheduleJob(jobDetail,trigger);

    //Start schedular
    scheduler.start();

MyJob.class

public class MyJob implements Job{

      @Override
      public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                 System.out.println("My Logic");
        }

    }
Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
  • 16
    Your `docs' refers to a third-party library... And the OP is asking about the setup of a cron job to launch a java program. You're seemingly setting up a job from within your code. – VH-NZZ Mar 04 '14 at 06:37
2

If you are using unix, you need to write a shellscript to run you java batch first.

After that, in unix, you run this command "crontab -e" to edit crontab script. In order to configure crontab, please refer to this article http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/

Save your crontab setting. Then wait for the time to come, program will run automatically.

Chi Nguyen
  • 89
  • 1
  • 8
  • I have tried this already. But this does not provide solution to run Java program in Cron.. – user3138111 Mar 04 '14 at 06:10
  • @user3138111: Why not? What line did you add? How about: `0 * * * * java -cp yourpath SomeClass` or `@hourly java -cp yourpath SomeClass` – VH-NZZ Mar 04 '14 at 06:35
  • I created a helloworld Java class to write a file it to a file. But I'm not able to see the output file getting generated. This is my cron Job text 1 * * * * java -cp HelloWorld . HelloWorld class contains the below text PrintWriter out = new PrintWriter(new FileWriter("/output.txt",true)); out.println("Ram"); out.close(); – user3138111 Mar 04 '14 at 17:02
  • 1
    create a **temp.sh** file. in **temp.sh**, you write script to run your java program. for example: `$JAVA_HOME/java -cp helloworld`. Then in crontab, you configure `00 2 * * * temp.sh >/dev/null 2>&1`. This configuration to make system run temp.sh everyday at 2 o'clock – Chi Nguyen Mar 05 '14 at 03:36