- 今天在实际工作中遇到了定时任务注解这个知识点,看了一下资料,整理一下,需要的同学可以大概参考,也为自己以后查阅记录这里。
- 有可能有些地方有bug,大神路过请指点提出。
@1在springMVC里使用spring的定时任务非常简单,在xml里加入task的命名空间
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">
@2启用注解驱动的定时任务
<task:annotation-driven scheduler="myScheduler"/>
@3配置定时任务的线程池(推荐配置线程池,若不配置多任务下会有问题:(spring的定时任务默认是单线程,多个任务执行起来时间会有问题(B任务会因为A任务执行起来需要10S而被延后10S执行);当我们配置了线程池后,(多线程下,B任务再也不会因为A任务执行起来要10S而被延后了))。
<task:scheduler id="myScheduler" pool-size="10"/>
@4写定时任务
@Scheduled注解为定时任务,cron表达式里写执行的时机
package com.zyyc.job;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.zyyc.utils.JawaGlobals;
import com.zyyc.utils.JdbcUtils;
/**
* Modified by zj on 2018/5/15.
*
* 创建设备心跳检测信息报警,每20分钟一次
*/
@Component
public class Heartbeat {
protected static final transient Logger Log = Logger.getLogger(Heartbeat.class);
private static Map<String, Integer> hearttemp= new HashMap<String,Integer>(20);
static{
hearttemp.put("cook", 1);
hearttemp.put("cook1", 0);
hearttemp.put("PM25", 1);
hearttemp.put("PM251", 0);
hearttemp.put("PM10", 1);
hearttemp.put("PM101", 0);