Spring简单的定时器

在我们项目配置文件(XML)中配置

xmlns:task="http://www.springframework.org/schema/task"  

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  

启动task

<task:annotation-driven scheduler="Scheduler"/> 

调用@Scheduled    cron为定时执行的时间

 @Scheduled(cron="0/10 * *  * * ? "

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架中,有多种方式可以实现定时任务调度。以下是Spring内置的定时器实现方式: 1. 使用`@Scheduled`注解:在需要执行定时任务的方法上添加`@Scheduled`注解,并配置相应的定时任务表达式。例如: ```java import org.springframework.scheduling.annotation.Scheduled; public class MyScheduledTask { @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨执行 public void myTask() { // 执行定时任务的逻辑 } } ``` 2. 实现`SchedulingConfigurer`接口:创建一个类实现`SchedulingConfigurer`接口,并重写`configureTasks`方法,用于配置定时任务。例如: ```java import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; @Configuration @EnableScheduling public class MyTaskConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { // 配置定时任务 taskRegistrar.addCronTask(() -> { // 执行定时任务的逻辑 }, "0 0 0 * * ?"); // 每天凌晨执行 } } ``` 3. 使用XML配置:在Spring的XML配置文件中使用`<task:scheduled>`标签来配置定时任务。例如: ```xml <beans xmlns:task="http://www.springframework.org/schema/task"> <task:scheduler id="myScheduler" pool-size="10" /> <task:scheduled ref="myTaskBean" method="myTask" cron="0 0 0 * * ?" /> <bean id="myTaskBean" class="com.example.MyTaskBean" /> </beans> ``` 这些是Spring内置的一些定时任务调度的实现方式,根据项目的需求和个人偏好,选择适合的方式来实现定时任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值