Menu

1 / 2

Spring @Scheduled running twice? Causes and fixes

DEV Community: java·Nilail·14 days ago
#fl04dVdd
#devtojava#devto#dev#spring#scheduled
Long article (1679 words) — no AI summary yet.
Reading 0:00
15s threshold

A Spring @Scheduled job that runs twice is usually running on two instances of the application, or on two instances of the same bean. @Async or virtual threads let its runs overlap, and a distributed lock released too early lets two nodes run it. Here is how to tell which one it is, reproduced on Spring Boot 4.1.2, and how to make the job run once.

Why does my @Scheduled job run twice?

Spring schedules a @Scheduled method once per bean instance, per running application . Every cause below breaks one of those two "once". The quickest way to tell them apart is to log, in the job itself, which process and which object ran it:

@Scheduled ( cron = "0 0 * * * *" ) void report ( ) { log . info ( "report in {} by {}" , ManagementFactory . getRuntimeMXBean ( ) . getName ( ) , // pid@host System . identityHashCode ( this ) ) ; // … }

Enter fullscreen mode

Exit fullscreen mode

Two different pid@host values in the log: the application runs twice. One process, two object identities: the bean exists twice.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.