spring进阶教程(三):定时任务

前言

前几节我们用第三方框架quarz实现了定时任务,实际上spring3.1开始,spring已经内置了定时任务的支持,实现非常简单,下面我们一起看看怎么实现

参考项目:https://github.com/bigbeef/cppba-sample
开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com

ScheduleApplication.java

其中重点是@EnableScheduling注解,表示启动定时任务支持

package com.cppba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }
}

SaySchedule.java

package com.cppba.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SaySchedule {

    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0/2 * * * * ?")
    public void sayHi() {
        System.out.println("hi!    time is :" + df.format(new Date()));
    }

    @Scheduled(cron = "1/2 * * * * ?")
    public void sayHello() {
        System.out.println("hello! time is :" + df.format(new Date()));
    }
}

核心重点是@Scheduled注解,@Scheduled支持多种类型的计划任务:cron、fixDelay、fixRate,最流行的还是cron表达式,
在这里推荐一个cron表达式在线生成器:http://cron.qqe2.com/


功能很强大,可以图形化配置cron表达式,也可以泛解析cron表达式的执行时间,特别方便

运行项目

控制台打印如下:

hi!    time is :2017-08-22 22:40:08
hello! time is :2017-08-22 22:40:09
hi!    time is :2017-08-22 22:40:10
hello! time is :2017-08-22 22:40:11
hi!    time is :2017-08-22 22:40:12
hello! time is :2017-08-22 22:40:13
hi!    time is :2017-08-22 22:40:14
hello! time is :2017-08-22 22:40:15
hi!    time is :2017-08-22 22:40:16
hello! time is :2017-08-22 22:40:17
hi!    time is :2017-08-22 22:40:18
hello! time is :2017-08-22 22:40:19
hi!    time is :2017-08-22 22:40:20
hello! time is :2017-08-22 22:40:21
hi!    time is :2017-08-22 22:40:22
hello! time is :2017-08-22 22:40:23
hi!    time is :2017-08-22 22:40:24

hello和hi交替执行,因为我们配置的cron表达式是:sayHi方法从0秒开始,每两秒执行一次;sayHello方法从1秒开始,每两秒执行一次。

到此,我们的定时任务运行成功!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 博客原文 徒手翻译spring framework 4.2.3官方文档的第33章,若有翻译不当之处请指正。 定时任...
    rabbitGYK阅读 5,674评论 4 24
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,282评论 25 708
  • 慢生活.淡味道 慢生活--慢节奏地生活。 “慢生活”一词,最早看到是在朱德庸的访谈中。喜欢朱德庸的漫画,更喜欢朱德...
    梅洛的听雨轩阅读 179评论 1 0
  • 第三十七章 回家之后余景灏把京东,淘宝之类的网站逛了无数圈,依然不知道要送平生什么。余景灏看着电脑发愁,万能的淘宝...
    星如雨雨雨阅读 312评论 0 0