配置文件
1在配置文件中添加schemal
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
<context:annotation-config />
<!-- spring扫描注解的配置 -->
<context:component-scan
base-package="实现类的包名" />
<!-- 开启这个配置,spring才能识别@Scheduled注解 -->
<task:annotation-driven scheduler="myScheduler" mode="proxy" />
<task:scheduler id="myScheduler" pool-size="10"/>
<!-- 自动扫描的包名 -->
<context:component-scan base-package="com.xxx">
</context:component-scan>
<!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射 -->
<mvc:annotation-driven />
2.实现类
package com.bigdataplatform.service.impl;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.bigdataplatform.dao.cwcountEntityMapper;
/**
*
* @author zhanglun
*
* @date 2018年7月30日 下午1:52:23
*/
@Service
@Component
@Lazy(false)
@EnableScheduling //4.0要加个该注解,否则定时任务不生效。
public class CwCountTaskServiceImpl {
private Logger logger = Logger.getLogger(CwCountTaskServiceImpl.class);
@Resource
private cwcountEntityMapper cwcountDao;
@Scheduled(cron = "0 1 2 1 * ? ") //每个月1号凌晨2点1分执行
public void insertCwRecords() {
logger.error("定时任务批量增加开始。。。。。。。。。。。");
try {
System.out.println("定时任务开始");
cwcountDao.insertCwRecords();
} catch (Exception e) {
logger.error("定时任务批量增加失败:::::" + e);
}
logger.error("定时任务批量增加结束。。。。。。。。。。。。。。");
}
}
注意: 项目启动后。会读取当前系统时间来进行计算后续执行的时间。
如果在项目启动后。再修改系统时间。任务还是会按照原来的时间来执行任务 。
* * * * * * *
秒 分 时 日 月 周 年