美文网首页
springboot定时任务的学习

springboot定时任务的学习

作者: 黑子_f338 | 来源:发表于2018-10-09 01:28 被阅读0次

定时任务的几种实现方式

1、使用Timer

public  class  MyTimer{

public  static  void main(String[] args) {

TimerTask timerTask =newTimerTask() {

            @Override

publicvoidrun() {

                LocalDateTime current = LocalDateTime.now();

String timeString = current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

System.out.println("task  run:"+ timeString);

            }

        };

Timer timer =newTimer();

//定时任务3秒后启动,每1秒执行一次

timer.schedule(timerTask,3000,1000);

    }

}

2、使用ScheduledExecutorService

该方法跟Timer类似,直接看demo:

public class TestScheduledExecutorService{

publicstaticvoidmain(String[] args){

        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

 参数:1、任务体 2、首次执行的延时时间

    3、任务执行间隔 4、间隔时间单位

service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+newDate()),0,3, TimeUnit.SECONDS);

    }

}

3、使用spring task

1、添加的依赖就是正常的spring依赖,在文章jpa进阶中可以翻查到

2、创建定时任务类,用@Scheduled注解写人物

3、在运行主类上添加@EnableScheduling注解开启对定时任务的支持

4、使用Quartz框架

这里只整理了SpringBoot版本2后的,因为由于他的封装。变得极为简单。

1、添加依赖

2、创建任务类,继承QuartzJobBean实现方法

3、创建配置类(用来配置,可以随放)

4、启动程序


二、多线程的实现

配置类:

在任务类添加@Async注解即可。

简单的定时发送邮件:https://shimo.im/docs/y28L75XR6zko6Ru1/

相关文章

网友评论

      本文标题:springboot定时任务的学习

      本文链接:https://www.haomeiwen.com/subject/ebrdaftx.html