JAVA-springboot 定时任务

本文介绍了如何在SpringBoot应用中配置和使用定时任务。通过在启动类启用@EnableScheduling注解,配合@Component和@Scheduled注解,可以实现周期性任务的执行。示例中展示了两种定时任务:一种是按照固定cron表达式执行,另一种是按固定间隔时间执行。示例代码中更新了数据库记录,并输出了执行成功的提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot 定时任务

启动类

@SpringBootApplication
@EnableScheduling //开启定时任务
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}
1.要在任务的类上写@Component
2.要在任务方法上写@Scheduled
3.cron 生成 https://www.bejson.com/othertools/cron/
@Component
public class Jobs {
	//固定时间执行
   @Scheduled(cron = "1 35 9 31 8 ?")// spring 3.0 后只支持 “6个参数”的cron。
    public void testTimer(){
        DictionaryEntry dictionaryEntry = dictionaryEntryService.findById(1);
        dictionaryEntry.setEntryRemark(dictionaryEntry.getEntryRemark() + "1");
        dictionaryEntryService.updateEntry(dictionaryEntry);
        System.out.println("定时任务执行成功" + "---  " + new Date());
    }

	//每隔30S执行
	@Scheduled(fixedRate = 30000)
    public void testTimer2(){
        DictionaryEntry dictionaryEntry = dictionaryEntryService.findById(1);
        dictionaryEntry.setEntryType(dictionaryEntry.getEntryType() + "2");
        dictionaryEntryService.updateEntry(dictionaryEntry);
        System.out.println("每30S定时任务执行成功");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值