1. Introduction
In this article, we are going to present cron expressions for executing tasks every 2 hours. Cron expression is a special format used for defining time for scheduled jobs.
2. Cron expression every 2 hours for crontab
In Linux there are a special crontab files used for cron jobs configuration. Each line in the crontab file contains six fields separated by a space followed by the command to be run. The cron expression for crontab daemons that execute task every 2 hours looks like the following:
The expression contains the following components:
0
- at minute 0,/2
- every 2 hours,- every day of the month,
- every month,
- every day of the week.
Example crontabs:
Run PHP script every 2 hours:
0 /2 /usr/bin/php /home/username/public_html/cron.php >/dev/null 2>&1
Create MySQL dump every hour:
0 /2 mysqldump -u root -pPASSWORD database > /root/db.sql >/dev/null 2>&1
Run bash script every hour:
0 /2 /bin/bash /home/username/backup.sh >/dev/null 2>&1
3. Cron expression every 2 hours for Spring Scheduler
In Spring scheduler a cron expression consists of six sequential fields: second, minute, hour, day of the month, month, day(s) of the week. In Spring cron expression use to run tasks in 2-hour intervals looks like the following:
Let's break down the expression into separate components:
0
- at second :00,0
- at minute :00,0/2
- starting at 0 every 2 hours,1/1
- starting at 1 every 1,*
- every month,?
- any day of the week.
Example Spring scheduler configuration that executes task every hour:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyScheduler {
@Scheduled(cron = "0 0 0/2 1/1 * ?")
public void doSomething() {
// this code will be executed every hour
}
}
4. Cron expression every 2 hours for Quartz
The Quartz is an open-source scheduling tasks library for Java application. Quartz expression has seven parameters: The last one stands for the year.
The following snippet creates a simple cron scheduler using Quartz library:
JobDetail job = newJob(SimpleJob.class)
.withIdentity("job1", "group1")
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0 0 0/2 1/1 ? "))
.build();
sched.scheduleJob(job, trigger);
5. Conclusion
In this article we presented several cron expression used for executing task every hour. Presented crons are ready to copy/paste.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}