转载《spring定时任务轮询(spring Task)》

亲测可用

原文网址:http://blog.csdn.net/wanglha/article/details/51026697

本博主注:xmlns:task="http://www.springframework.org/schema/task"

原文:

定时任务轮询比如任务自服务器启动就开始运行,并且每隔5秒执行一次。

以下用spring注解配置定时任务。
1、添加相应的schema

  

完整schema如下:

  

2、配置自动调度的包和定时开关

1
2
3
4
5
6
<!-- 注解扫描包 -->
<context:component-scan base-package="com.ljq.web.controller.annotation" />
<!-- Enables the Spring Task @Scheduled programming model -->
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />

  

3、添加调度测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.ljq.web.controller.annotation;
 
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
/**
 * 调度测试类(每隔5秒执行一次)
 *
 * @author Administrator
 *
 */
@Service
public class TaskTest {
    @Scheduled(cron = "0/5 * * * * ? ")
    public void myTestWork() {
        System.out.println(System.currentTimeMillis());
    }
}

20180707

可用@Component代替@Service,以注入Service层

package com.bjbr.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.bjbr.service.SendWxService;

@Component
@Lazy(false)
public class SendWxTask {
    private static final Logger logger = LoggerFactory.getLogger(SendWxTask.class);
    @Autowired
    private SendWxService sendWxService;
    /**
     * @todo 每天七点
     * @author zhangyanan
     * @datetime 2018年7月3日下午5:09:31
     */
    @Scheduled(cron = "0 0 7 * * ?")
    public void everyDayWork() {
        logger.debug("----------进入everyDayWork提醒------------");
    }
}

可以看到cron表达式与之前的不同,新手可能不懂,解释一下

cron = "0 0 7 * * ?"
cron = "0/5 * * * * ? "

String []s=cron.split(" ");
s[0]:秒
s[1]:分
s[2]:时
s[3]:日
s[4]:月
s[5]:星期
【s[6]
】:年
注意s[6],cron表达式在线生成器是可以解析运行的,但实际情况并不是
@这篇文章以源码的形式展示了spring cron表达式只支持6 fields,实际运用的时候不要出现
cron = "0 0 7 * * ? 2018"这样的形式,否则会报异常:
java.lang.IllegalArgumentException: cron expression must consist of 6 fields (found 7 in******


附:cron表达式在线生成器
原文地址:https://www.cnblogs.com/yanan7890/p/8621870.html