如何在同一方法配置多@Scheduled实现2秒和5秒间隔执行?
Got it, let's figure out how to make your check() method run both every 2 seconds and every 5 seconds with Spring's @Scheduled annotation. Here are a couple of simple, effective ways to do this:
Approach 1: Multiple @Scheduled Annotations on the Same Method
If you're using Spring 4.1 or newer (which most projects are these days), you can apply multiple @Scheduled annotations directly to your single check() method. This is the cleanest, most concise approach.
First, update your method to include both cron-triggered schedules:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class YourSchedulerBean { private static final Logger LOGGER = LoggerFactory.getLogger(YourSchedulerBean.class); @Scheduled(cron = "${cron.startdate.2s}") @Scheduled(cron = "${cron.startdate.5s}") public void check() { LOGGER.info("1 - Check DB"); } }
Then adjust your application.yml to define both cron expressions:
cron: startdate: 2s: "0/2 * * * * *" 5s: "0/5 * * * * *"
Spring will create two separate scheduled tasks here—one firing every 2 seconds, the other every 5 seconds—both calling your check() method. You’ll get exactly the log pattern you want: runs at 00, 02, 05, 07, 10, etc.
Approach 2: Wrapper Methods for Older Spring Versions
If you’re stuck on a Spring version before 4.1 (which doesn’t support multiple @Scheduled annotations on a single method), no problem. Just extract your core database check logic into a private method, then create two scheduled wrapper methods that call it:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class YourSchedulerBean { private static final Logger LOGGER = LoggerFactory.getLogger(YourSchedulerBean.class); @Scheduled(cron = "${cron.startdate.2s}") public void checkEvery2Seconds() { performDbCheck(); } @Scheduled(cron = "${cron.startdate.5s}") public void checkEvery5Seconds() { performDbCheck(); } private void performDbCheck() { LOGGER.info("1 - Check DB"); } }
Use the same application.yml as Approach 1. This keeps your logic DRY (Don’t Repeat Yourself) while working with older Spring versions.
Quick Side Note
If you don’t need the flexibility of cron expressions (e.g., you just need fixed time intervals), you could also use fixedRate instead of cron:
@Scheduled(fixedRate = 2000) // 2 seconds @Scheduled(fixedRate = 5000) // 5 seconds public void check() { LOGGER.info("1 - Check DB"); }
But since you’re already using cron (which makes it easier to adjust schedules later if needed), sticking with your original pattern is totally fine.
内容的提问来源于stack exchange,提问作者Javi HG

