springBoot定时任务处理类的实现代码
时间:2021-09-25 08:18:25|栏目:JAVA代码|点击: 次
首先在启动类上添加注解:@EnableScheduling 来开启定时任务
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后新建定时任务类
@Component
public class QuartzService {
/**
* 通过时间表达式执行定时任务
*/
@Scheduled(cron = "0 0/1 * * * ?")
public void timerToNow(){
System.out.println("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
/**
*启动时间点之后 X毫秒秒执行一次
*/
@Scheduled(fixedRate = 5000)
public void timerToZZP(){
System.out.println("fixedRate:" + new Random().nextLong() + new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
/**
* 结束时间点之后 每X毫秒执行一次
*/
@Scheduled(fixedDelay = 10000)
public void timerToReportCount(){
System.out.println("fixedDelay:" + new Random().nextLong() + new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
/**
* 第一次延迟 X毫秒执行,之后按照fixedRate的规则每X毫秒执行
*/
@Scheduled(initialDelay = 10000,fixedRate = 6000)
public void timerToReport(){
System.out.println("initialDelay:" + new Random().nextLong() + new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}
启动项目,定时任务开始
总结


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




