Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Java cron job [duplicate]

Tags:

java

cron

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.

like image 525
user3138111 Avatar asked Mar 04 '14 05:03

user3138111


People also ask

How do I create a cron job in Java?

Java Cron ExpressionThe @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. The @Scheduled annotation is used to trigger the scheduler for a specific time period.

Can two cron jobs run at the same time?

We can run several commands in the same cron job by separating them with a semi-colon ( ; ). If the running commands depend on each other, we can use double ampersand (&&) between them. As a result, the second command will not run if the first one fails.

How do I run a cron job every second?

“cron run every second” Code Answer's*/10 * * * * * will run every 10 sec.


2 Answers

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");    }  } 
  • Timer

  • TimerTask

Alternative You can also use ScheduledExecutorService.

like image 160
Indrajith Avatar answered Sep 25 '22 22:09

Indrajith


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");         }      } 
like image 44
Shoaib Chikate Avatar answered Sep 26 '22 22:09

Shoaib Chikate