一、序言:

最近项目需要用到定时任务,需要完成一个定时功能。经过了解,项目中目前实现定时任务,一般有三种选择,一是用Java自带的timer类。稍微看了一下,可以实现大部分的指定频率的任务的调度(timer.schedule()),也可以实现关闭和开启(timer.cancle)。但是用其来实现某天的某个时间或者某月的某一天调度任务有点不方便。

二是采用Quartz 调度器实现。这是一个功能很强大的开源的专门用于定时任务调度的框架,也很好的和springboot整合,缺点:配置复杂,需要花费一定的时间去了解和研究。

三是spring3.0以后自带的scheduletask任务调度,可以实现quartz的大部分功能,不需要额外引用jar,也不需要另外配置。而且支持注解和配置文件两种。

我选择的是最直接简单的第三种。下面简单介绍下springboot自带的定时器来实现定时任务。

二、定时任务代码:

简单介绍:开启和关闭相当于写出一个个接口,暴露给前端,通过页面来实现定时器 的开关操作。由于我是后台开发人员,这里只给出后台代码。

1、controller层代码:

package com.left.controller;

import com.left.Result;

import com.left.runnable.MyRunnable1;

import com.left.runnable.MyRunnable2;

import com.left.util.ResultUtils;

import com.left.utils.YouXinConfiguration;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.scheduling.Trigger;

import org.springframework.scheduling.TriggerContext;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import org.springframework.scheduling.support.CronTrigger;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

import java.util.concurrent.ScheduledFuture;

/**

*

* @author : orange

* @e-mail : [email protected]

* @time : 2018/8/28 16:15

* @desc : 定时任务

* @version: 1.0

*

*/

@Slf4j

@RestController

@Api(description = "定时任务")

@RequestMapping("/quartz/task")

public class DynamicTaskController {

@Autowired

private YouXinConfiguration youXinConfiguration;

@Autowired

private ThreadPoolTaskScheduler threadPoolTaskScheduler;

private ScheduledFuture> future1;

private ScheduledFuture> future2;

@Bean

public ThreadPoolTaskScheduler threadPoolTaskScheduler() {

return new ThreadPoolTaskScheduler();

}

@PostMapping("/startCron1")

@ApiOperation("开始定时任务1")

public Result startCron1() {

future1 = threadPoolTaskScheduler.schedule(new MyRunnable1(),new Trigger(){

@Override

public Date nextExecutionTime(TriggerContext triggerContext){

return new CronTrigger(youXinConfiguration.getCorn1()).nextExecutionTime(triggerContext);

}

});

System.out.println("DynamicTask.startCron1()");

return ResultUtils.success();

}

@PostMapping("/stopCron1")

@ApiOperation("关闭定时任务1")

public Result stopCron1() {

if (future1 != null) {

future1.cancel(true);

}

System.out.println("DynamicTask.stopCron1()");

return ResultUtils.success();

}

@PostMapping("/startCron2")

@ApiOperation("开始定时任务2")

public Result startCron2() {

future2 = threadPoolTaskScheduler.schedule(new MyRunnable2(),new Trigger(){

@Override

public Date nextExecutionTime(TriggerContext triggerContext){

return new CronTrigger(youXinConfiguration.getCorn2()).nextExecutionTime(triggerContext);

}

});

System.out.println("DynamicTask.startCron2()");

return ResultUtils.success();

}

@PostMapping("/stopCron2")

@ApiOperation("关闭定时任务2")

public Result stopCron2() {

if (future2 != null) {

future2.cancel(true);

}

System.out.println("DynamicTask.stopCron2()");

return ResultUtils.success();

}

}

这里面我写了两组定时器的开关操作。这层代码中所引用类的介绍:

ThreadPoolTaskScheduler:线程池任务调度类,能够开启线程池进行任务调度。ThreadPoolTaskScheduler.schedule()方法会创建一个定时计划ScheduledFuture,在这个方法需要添加两个参数,Runnable(线程接口类) 和CronTrigger(定时任务触发器)

YouXinConfiguration:自己写的读取yml文件中数据的类,我是通过这个类来读取yml文件中cron时间表达式的,从而可以达到定时时间可配置的效果。当然了也可以把这个时间表达式写成通过前端页面传入的形式。但是我觉得这种时间参数改动频率很小,写在yml配置文件足以。这个类下面会给出代码。

MyRunnable1与MyRunnable2类:这两个类都是实现了Runnable接口,重写了run方法,定时任务的逻辑代码就是在这个里面实现的。代码会在下面给出。

2、YouXinConfiguration类代码:

package com.left.utils;

import lombok.Data;

import lombok.EqualsAndHashCode;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.stereotype.Component;

/**

*

* @author : orange

* @e-mail : [email protected]

* @time : 2018/8/28 16:15

* @desc :

* @version: 1.0

*

*/

@Data

@Component

@ConfigurationProperties(prefix = "youxing")

@EqualsAndHashCode(callSuper = false)

public class YouXinConfiguration {

private String corn1;

private String corn2;

}

3、yml文件(定时时间的配置的在最下面的youxing字段)

server:

port: 8002

spring:

application:

name: dubbo-client-orange

redis:

database: 0

host: 127.0.0.1

port: 6379

password:

jedis:

pool:

max-active: 8

max-wait: -1

max-idle: 8

min-idle: 0

timeout: 10000

dubbo:

server: false

registry: redis://127.0.0.1:6379

consumer:

check: false

timeout: 10000

youxing:

corn1: 0/10 * * * * ?

corn2: 0/5 * * * * ?

4、MyRunnable1与MyRunnable2基本一样:

package com.left.runnable;

import java.text.SimpleDateFormat;

import java.util.Date;

public class MyRunnable1 implements Runnable {

@Override

public void run() {

System.out.println("first DynamicTask," + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

}

}

package com.left.runnable;

import java.text.SimpleDateFormat;

import java.util.Date;

public class MyRunnable2 implements Runnable {

@Override

public void run() {

System.out.println("second DynamicTask," + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

}

}

6、控制台打印效果:

java定时开始和关闭_springboot自带定时器实现定时任务的开启关闭以及定时时间可以配置详解...相关推荐

  1. springboot自带定时器实现定时任务的开启关闭以及定时时间可以配置

    一.序言: 最近项目需要用到定时任务,需要完成一个定时功能.经过了解,项目中目前实现定时任务,一般有三种选择,一是用Java自带的timer类.稍微看了一下,可以实现大部分的指定频率的任务的调度(ti ...

  2. java centertoscreen_java screen的配置详解及注意事项

    java screen的配置详解及注意事项 # Set default encoding using utf8 defutf8 on ## 解决中文乱码,这个要按需配置 defencoding utf ...

  3. Burp Suite安装配置详解(附Java 环境安装)

    Burp Suite安装配置详解 1.Java 安装与环境配置详解 1.0 下载Java SDK 1.8 最新版 2.0 配置Java 环境变量 2.Burp Suite 安装详解 2.0 下载Bur ...

  4. Java web之web.xml配置详解

    什么是web.xml web.xml是web项目的配置文件,一般的web工程都会用到web.xml来配置,方便大型开发.web.xml主要用来配置Filter,Listener,Servlet等.但是 ...

  5. java 配置jmstemplate_SpringBoot集成JmsTemplate(队列模式和主题模式)及xml和JavaConfig配置详解...

    1.导入jar包: org.springframework.boot spring-boot-starter-activemq org.apache.activemq activemq-pool 2. ...

  6. phpstudy的php fpm,PHP_php-fpm配置详解,php5.3自带php-fpm复制代码 代码 - phpStudy

    php-fpm配置详解 php5.3自带php-fpm /usr/local/php/etc/php-fpm.conf pid = run/php-fpm.pid pid设置,默认在安装目录中的var ...

  7. java log4j基本配置及日志级别配置详解,java基础面试笔试题

    我总结出了很多互联网公司的面试题及答案,并整理成了文档,以及各种学习的进阶学习资料,免费分享给大家. 扫描二维码或搜索下图红色VX号,加VX好友,拉你进[程序员面试学习交流群]免费领取.也欢迎各位一起 ...

  8. java图片填充父容器_java相关:spring的父子容器及配置详解

    java相关:spring的父子容器及配置详解 发布于 2020-5-26| 复制链接 本篇文章主要介绍了spring的父子容器及配置详解,详细的介绍了spring父子容器的概念.使用场景和用法,有兴 ...

  9. java JDK安装与环境配置详解(超超超级详细)

    点击以下链接获取详细图文教程! java JDK安装与环境配置详解 https://v.xiumi.us/board/v5/3QTAV/112689421

最新文章

  1. php的基本语法和数据类型
  2. 差异表达基因-火山图和聚类图解释
  3. Confluence 6 SQL Server 测试你的数据库连接
  4. PCB Editor 布线后操作
  5. UA PHYS515A 电磁理论V 电磁波与辐射11 简单辐射问题 电偶极子的辐射
  6. Chrome 中的 JavaScript 断点设置和调试技巧
  7. 生活中处处有joke!!
  8. matlab 6.5 设计数字滤波器
  9. Java方法中的参数太多,第8部分:工具
  10. 【Java8】Stream 由函数生成流:创建无限流 - 实现斐波纳契数列
  11. python中reversed函数,Python3
  12. android studio 快捷键修改
  13. matlab绘制直方图的方法
  14. 木瓜移动每日快讯0511:谷歌Chrome引入新隐私功能fenced frame
  15. 魔百盒CM311-1_S905L3芯片_YST代工_红外蓝牙语音_安卓9.0_线刷固件包
  16. java集合框架之集合工具类Arrays类
  17. windows播放函数PlaySound
  18. Cocos2d-x初级篇之工程的创建和编译(windows环境)
  19. iTab新标签页,一款个性化的浏览器起始页插件
  20. 这里有你最想掌握的区块链技术

热门文章

  1. R in Action 学习笔记 - 第九章-Analysis of Variance
  2. 《Oracle PL/SQL实例精讲》学习笔记1——数据准备
  3. 战高端,荣耀亮出“第二把剑”
  4. 原来,这就是爱情的模样!
  5. ROS基础四之roscpp/rospy节点编写
  6. 持续集成(第二版) Martin Fowler著
  7. time.Timer
  8. 佬,速速进来观看你的专属通讯录(静态版本)
  9. 高斯判别分析(GDA)——含python代码
  10. Veil+tdm-gcc免杀360火绒瑞星