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定时任务执行成功");
}
}