在很多时候,我们会需要执行一些定时任务 ,Spring团队提供了Spring Task模块对定时任务的调度提供了支持,基于注解式的任务使用也非常方便。

只要跟需要定时执行的方法加上类似 @Scheduled(cron = "0 1 * *  *  *") 的注解就可以实现方法的定时执行。

cron 是一种周期的表达式,六位从右至左分别对应的是年、月、日、时、分、秒,数字配合各种通配符可以表达种类丰富的定时执行周期。

/**
* Cron Example patterns:
* <li>"0 0 * * * *" = the top of every hour of every day.</li>
* <li>"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.</li>
* <li>"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.</li>
* <li>"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays</li>
* <li>"0 0 0 25 12 ?" = every Christmas Day at midnight</li>
*/

基于注解的使用案列:

import org.springframework.stereotype.Component; 

@Component(“task”)
public class Task {
@Scheduled(cron = "0 1 * * * *") // 每分钟执行一次
public void job1() {
System.out.println(“任务进行中。。。”);
}
}

基于注解方式的定时任务,启动会依赖于系统的启动。如果需要通过代码或前台操作触发定时任务,就需要进行包装了。

下面是一个可以直接提供业务代码调用的定时任务调度器。调用 schedule(Runnable task, String cron) 传入要执行的任务

task和定时周期cron就可以了。注:基于注解方式需要在注解扫描范围内。

package com.louis.merak.schedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component; @Component
public class MerakTaskScheduler { @Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler; @Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
return new ThreadPoolTaskScheduler();
} /**
* Cron Example patterns:
* <li>"0 0 * * * *" = the top of every hour of every day.</li>
* <li>"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.</li>
* <li>"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.</li>
* <li>"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays</li>
* <li>"0 0 0 25 12 ?" = every Christmas Day at midnight</li>
*/
public void schedule(Runnable task, String cron){
if(cron == null || "".equals(cron)) {
cron = "0 * * * * *";
}
threadPoolTaskScheduler.schedule(task, new CronTrigger(cron));
} /**
* shutdown and init
* @param task
* @param cron
*/
public void reset(){
threadPoolTaskScheduler.shutdown();
threadPoolTaskScheduler.initialize();
} /**
* shutdown before a new schedule operation
* @param task
* @param cron
*/
public void resetSchedule(Runnable task, String cron){
shutdown();
threadPoolTaskScheduler.initialize();
schedule(task, cron);
} /**
* shutdown
*/
public void shutdown(){
threadPoolTaskScheduler.shutdown();
}
}

如果是需要通过前台操作调用RESTful执行定时任务的调度,使用以下Controller即可。

package com.louis.merak.common.schedule;

import java.text.SimpleDateFormat;
import java.util.Date; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController
public class MerakTaskSchedulerController { @Autowired
MerakTaskScheduler taskScheduler; @RequestMapping("/schedule")
public String schedule(@RequestParam String cron) {
     if(cron == null) {
       cron = "0/5 * * * * *";
}
        Runnable runnable = new Runnable() {
public void run() {
String time = new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date());
System.out.println("Test GETaskScheduler Success at " + time);
}
};
taskScheduler.schedule(runnable, cron);
return "Test TaskScheduler Interface.";
}
}

作者:朝雨忆轻尘
出处:https://www.cnblogs.com/xifengxiaoma/
版权所有,欢迎转载,转载请注明原文作者及出处。

基于Spring Task的定时任务调度器实现的更多相关文章

  1. SpringBoot2 task scheduler 定时任务调度器四种方式

    github:https://github.com/chenyingjun/springboot2-task 使用@EnableScheduling方式 @Component @Configurabl ...

  2. 2. SOFAJRaft源码分析—JRaft的定时任务调度器是怎么做的?

    看完这个实现之后,感觉还是要多看源码,多研究.其实JRaft的定时任务调度器是基于Netty的时间轮来做的,如果没有看过Netty的源码,很可能并不知道时间轮算法,也就很难想到要去使用这么优秀的定时调 ...

  3. 记录对定时任务调度器的小小改进 - API调度计划

    之前记录过一篇 [开源一个定时任务调度器 webscheduler],这是一个看似简单的小工具,昨天部署到服务器上开始试用下,听听反馈. 项目经理看过后,立马反馈说这个使用 Cron表达式 的计划太难 ...

  4. spring任务执行器与任务调度器(TaskExecutor And TaskScheduler)

    对于多线程及周期性调度相关的操作,spring框架提供了TaskExecutor和TaskScheduler接口为异步执行和任务调度.并提供了相关实现类给开发者使用.(只记录采用注解的使用形式,对于X ...

  5. 基于spring的quartz定时框架,实现简单的定时任务功能

    在项目中,经常会用到定时任务,这就需要使用quartz框架去进行操作. 今天就把我最近做的个人主页项目里面的定时刷新功能分享一下,很简单. 首先需要配置一个配置文件,因为我是基于spring框架的,所 ...

  6. 开源一个定时任务调度器 webscheduler

    在企业应用中定时任务调度的需求是必不可少的,比如定时同步数据,定时结转数据,定时检测异常等等.公司之前是在使用一款采用.net 开发的windows服务形式的定时程序,基本能满足需求,在一段时间的时候 ...

  7. 基于Redis实现分布式定时任务调度

    项目开发过程中,难免会有许多定时任务的需求进来.如果项目中还没有引入quarzt框架的情况下,我们通常会使用Spring的@Schedule(cron="* * * * *")注解 ...

  8. spring task 实现定时执行(补充:解决定时任务执行2次问题)

    首先在spring-mvc.xml配置头文件引入: xmlns:task="http://www.springframework.org/schema/task" 其次引入task ...

  9. spring中的定时任务调度用例

    在application-quartz.xml配置文件中添加如下配置信息: <!-- Quartz -->     <bean id="getSendEmailObject ...

随机推荐

  1. (匹配 匈牙利)棋盘游戏 -- Hdu --1281

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=1281 http://acm.hust.edu.cn/vjudge/contest/view.action ...

  2. STL---规范

    1. "插入操作" 新插入的数据位于‘哨兵迭代器“所指的节点的前方,并返回指向新插入位置的‘迭代器(指针)“.这是STL对于插入操作的标准规范. 2.链表操作 对于一个链式表,如果 ...

  3. log.debug(e.getMessage());

    private static final Log log = LogFactory.getLog(AbcAction.class); @ManagedProperty(name = "abc ...

  4. abp+angular+bootstrap-table的使用

    问题 materialize与bootstrap框架样式冲突 问题描述 在abp模板项目中引入bootstrap-table,列设置为checkbox,checkbox无法显示. 使用firefox浏 ...

  5. win10 打开sql server配置管理器

    win10 安装 sql server之后无法在开始菜单找到“sql server 配置管理器(SQL server configuration manager 1)在开始菜单中,无法找到 配置管理器 ...

  6. C#深入浅出获取时间DateTime

    首先,先了解微软.net里面的DateTime的DateTime.Now.DateTime.Now.Date.DateTime.Now.Day.DateTime.Now.DayOfWeek.DateT ...

  7. 面向对象进阶-item系列、__new__、__hash__、__eq__ (四)

    item系列 dic = {'k':'v'}# 对象 : 存储属性 和调用方法dic['k'] = 'v'# class Foo:#     def __init__(self,name,age,se ...

  8. xiaocong/uiautomator

    uiautomator      This module is a Python wrapper of Android uiautomator testing framework. It works ...

  9. linux 中定时执行python脚本

    一.让Python随Linux开机自动运行 准备好要自启的脚本auto.py 用root权限编辑以下文件 sudo vim /ect/rc.local 在exit 0上面编辑启动脚本的命令(编辑rc. ...

  10. java的类继承(与c++对比)

    1. interface的引入 使用interface来定义某一类通用操作,而又不强制规定其实现,对于Java的流行真是太重要了. 以JDBC举例.在Java之前,C++与数据库建立连接,常用的一个技 ...