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.
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.
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.
“cron run every second” Code Answer's*/10 * * * * * will run every 10 sec.
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.
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With