spring 4.0定时任务

本文介绍了如何在Spring 4.0中配置和使用定时任务,详细讲解了配置文件和实现类的设置。值得注意的是,项目启动后,定时任务将根据启动时的系统时间进行计算,即使之后修改系统时间,任务也会按原计划执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置文件

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("定时任务批量增加结束。。。。。。。。。。。。。。");
    }
}

注意: 项目启动后。会读取当前系统时间来进行计算后续执行的时间。
如果在项目启动后。再修改系统时间。任务还是会按照原来的时间来执行任务 。
* * * * * * *
秒 分 时 日 月 周 年

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值