Explain Codes LogoExplain Codes Logo

Spring cron expression for every day 1:01 am

java
cron-expressions
spring-framework
scheduling
Nikita BarsukovbyNikita Barsukov·Oct 9, 2024
TLDR

To schedule a job in Spring Framework for 1:01 AM every day, use the cron expression: "0 1 1 * * ?".

  • 0: stands for 'exactly on the dot', like in '12 PM sharp'
  • 1 minute
  • 1 AM
  • The task will run every day.

Refer to this effective Spring code snippet:

@Scheduled(cron = "0 1 1 * * ?") public void dailyJob() { // Code to keep your app lively at ungodly 1:01AM! }

Deciphering Spring cron expressions

Spring cron expressions are like a universal language for time, albeit a cryptic one. A typical expression has six fields. Let's arbitrarily translate this to Martian:

Field | Martian representation --------------- | ---------------------- 1. Seconds | 0–59, the *tick-tocks* of a minute 2. Minutes | 0–59, the *slices* on the hour pie 3. Hours | 0–23, or daily *candle* progression 4. Day of month | 1–31, or lunar *calendar flips* 5. Month | 1–12 or JAN–DEC, seasonal *shifts* 6. Day of week | 0–7 or SUN–SAT (0 or 7 is SUN), weekly *world spins*

Ensure the seconds field starts with "0" in your Spring cron pattern to stop time slipping through your code.

Time traveling: Scheduling across time zones

The 'Zone' attribute in @Scheduled is your time traveling ticket, should your server or job operate across time zones. Dial back or forward with the zone:

@Scheduled(cron = "0 1 1 * * ?", zone = "Europe/London") public void dailyJob() { // The queen's guard salutes: "It's tea time, mate!" }

Gear check: Spring framework version

Engines run smoothly with the right parts and updates. Your Spring framework version should ideally be 4.0.7.RELEASE or newer for the best scheduling experience.

Practical Tips and Watch-outs

  1. Validate and simulate: Platforms like cronmaker.com are cron's best buddies. They validate, simulate and even suggest cron expressions.
  2. Step aside, steps: Step values (* /step) in the day-of-week field won't step with you in Spring CronTrigger. Handle with care.
  3. Twisted twins: The day-of-week and the month field often perform parent trap stunts. Always cross-verify these values.
  4. Detective hats on: If tasks fire at odd times, play Sherlock with your minute and seconds fields. Quite the plot twirlers, those two!