Java Cron Expressions example

java cron exampleCron is a powerful Unix tool for scheduling. In Java there’s a class called CronTrigger for using cron scheduling.

This class uses cron expressions that were designed to provide agility to scheduling functionality.


Cron Expressions example in Java

Cron expression is a string containing special symbols separated with spaces. Such symbols represent different fields for scheduler configuration like month of a year, hour of a day, etc.

The order of configured fields is:

  • Seconds
  • Minutes
  • Hours
  • Day of month
  • Month
  • Day of week
  • Year

These expressions contain Let’s look at an easiest basic example:

* * * * * * *

This example uses a standard cron special character – *. It is used to specify that schedule task should be executed in every iteration (in all values) of this period. In our case the cron scheduler will be triggered every second of every minute of every hour of every day of a year.

Other Common Cron Expression Special Characters

? – specifies that field does not have a specific value

 – specifies ranges

, – is an analog for AND clause. Helps to specify additional values.

/ – specifies increments. Setting  seconds of minute field to 5/10 means to run starting from 5th second with step of 10 (5, 15, 25, 35, 45, 55)

L – last value in allowed range (can be applied to day of month and day of week).

W – specifies the nearest weekday from range Monday – Friday.

# – specifies the Nth day of the month. Value of 2#3 in field day of week means every third Monday of the month.

Another example:

0 30 12 ? * TUE-FRI

Such expression should be triggered at 12:30am every Tuesday, Wednesday, Thursday and Friday.

Leave a Reply

Be the First to Comment!