7

We have a requirement of running a job on 1st of every month (time: 00:00:00 AM) exactly.
We are using Spring framework's ScheduledTimerTask to schedule jobs using delay and period properties. This class doesn't support running a job on specific date.

Can somebody suggest, how we can solve that problem using Spring and Java technology?

informatik01
  • 16,038
  • 10
  • 74
  • 104
dvrnaidu
  • 151
  • 1
  • 1
  • 9

3 Answers3

17

If you don't have to run this job on a single node in a cluster you can use Spring Task, see: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

@Scheduled(cron="0 0 0 1 1/1 *")
public void doSomething() {
    // something that should execute on 1st day every month @ 00:00
}

For generating cron expressions try cronmaker.com

Please be aware that if you use this code in a cluster it will run on all nodes.

informatik01
  • 16,038
  • 10
  • 74
  • 104
rgrebski
  • 2,354
  • 20
  • 29
  • 3
    the cron expression throws exception "cron expression must consist of 6 fields (found 7..." because Spring cron format is different than unix (http://stackoverflow.com/questions/30887822/spring-cron-vs-normal-cron) – Kaizar Laxmidhar Oct 28 '15 at 14:14
  • According to https://crontab.guru/#0_0_0_1_1/1_* the expression is not valid always. – thinwybk Oct 09 '22 at 11:03
  • @thinwybk Cron tab and Scheduled both follows different syntax. – Rajesh Gupta Feb 20 '23 at 08:19
1

Since v5.3 Spring supports macros which represent commonly used sequences. See: New in Spring 5.3: Improved Cron Expressions

In your case you could use:

@Scheduled(cron = "@monthly")
public void task() {
    // your task
}

which is the same as writing this:

@Scheduled(cron = "0 0 0 1 * *")
public void task() {
    // your task
}
0

You can use Quartz Scheduler. It integrates great with Spring.

http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/tutorial-lesson-06

peter.petrov
  • 38,363
  • 16
  • 94
  • 159