前言
在开发中,经常需要执行定时任务,例如定时发送邮件、定时清理缓存等。
Spring框架提供了@Scheduled注解,可以方便地实现定时任务的调度和执行。
本文将详细介绍@Scheduled注解的属性和使用示例。
一、属性说明
@Scheduled注解的属性
cron
:用于指定Cron表达式,表示任务的执行时间规则。
示例:@Scheduled(cron = "0 0 0 * * ?")
表示每天凌晨执行任务。
zone
:用于指定时区,默认为服务器的时区。
示例:@Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Shanghai")
表示每天凌晨执行任务,时区为上海。
fixedDelay
:用于指定任务执行结束后的延迟时间,单位为毫秒。
示例:@Scheduled(fixedDelay = 5000)
表示任务执行结束后延迟5秒再次执行。
fixedDelayString
:与fixedDelay属性相同,但使用字符串形式表示延迟时间。
示例:@Scheduled(fixedDelayString = "PT5S")
表示任务执行结束后延迟5秒再次执行。
fixedRate
:用于指定任务执行的频率,单位为毫秒。
示例:@Scheduled(fixedRate = 10000)
表示每隔10秒执行一次任务。
fixedRateString
:与fixedRate属性相同,但使用字符串形式表示频率。
示例:@Scheduled(fixedRateString = "PT10S")
表示每隔10秒执行一次任务。
initialDelay
:用于指定任务首次执行的延迟时间,单位为毫秒。
示例:@Scheduled(initialDelay = 3000, fixedRate = 5000)
表示首次延迟3秒,然后每隔5秒执行一次任务。
initialDelayString
:与initialDelay属性相同,但使用字符串形式表示延迟时间。
示例:@Scheduled(initialDelayString = "PT3S", fixedRate = 5000)
表示首次延迟3秒,然后每隔5秒执行一次任务。
CRON_DISABLED
:用于表示禁用Cron表达式的特殊值。
示例:@Scheduled(cron = Scheduled.CRON_DISABLED)
表示禁用Cron表达式。
这些属性可以根据实际需求进行组合使用,以实现不同的定时任务调度策略。
二、Cron在线表达式生成器工具
三、使用示例
在启动类添加@EnableScheduling
注解,表示开启定时器(在其它组件上添加注解也是可以的)
@SpringBootApplication
@EnableScheduling
public class ScheduledApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ScheduledApplication.class, args);
}
}
使用@Scheduled注解需要在类上添加@Service、@Component或其他类似的注解。这是因为@Scheduled注解是Spring框架提供的,它需要被Spring容器扫描并管理。
通过在类上添加@Service、@Component等注解,将该类标识为一个Spring组件,使得Spring容器能够自动扫描并实例化该类,并将其纳入到容器的管理范围内。这样,@Scheduled注解才能生效,定时任务才能被正确地执行。
除了@Service、@Component,还可以使用其他的注解,如@Controller、@Repository等,具体使用哪个注解取决于类的功能和用途。这些注解都是Spring框架提供的,用于标识和管理不同类型的组件。
@Component
public class ScheduleManager {
@Scheduled(cron = "0 10 0 * * *")
public void test() {
// 执行逻辑
}
}
四、多环境配置定时器
Scheduled.CRON_DISABLED
的值为"-"
,即@Scheduled(cron = "-")
,表示该定时器不执行
可用于开发环境与生产环境的控制,示例:
@Scheduled(cron = "${cron.test}")
private void test() {
// 执行
}
# application-prod.yml
cron:
test: 0 0 12 * * ? # 每天12点执行一次
# application-dev.yml
cron:
test: '-' # 不执行
运行时切换配置环境该文章进行了讲解:Java 运行jar包变更配置文件与变量