[Java]SpringMVC开启排程,实现定时任务

2021-08-03 919点热度 0人点赞 0条评论

SpringMVC的Java程序中,希望能定时执行一些任务,例如每隔一定时间,或者每天定时执行一个方法等等。

如果你使用的是SpringBoot,请参考:https://blog.terrynow.com/2021/07/10/java-spring-springboot-schedule-implement/

实现

SpringMVC中的配置要稍微比SpringBoot多一些配置

首选修改application-context.xml(这个文件可能会根据你web.xml里的contextConfigLocation的设置的不同,可以根据自己的实际情况修改)

头部引入命令空间:

xmlns:task="http://www.springframework.org/schema/task

增加xsd:

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd

开启task注释的自动扫描装载

<task:annotation-driven/>

完整的application-context.xml示例如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task.xsd">

    <context:annotation-config/>
    
    <task:annotation-driven />

</beans>

新建一个ScheduledTask.java 加上@Component注解

@Component
public class ScheduledTask {

    private static final Log log = LogFactory.getLog(ScheduledTask.class);

    // 如果要操作数据库或者引入Service
    @Resource(name = "systemService")
    private ISystemService systemService;

    //每一分钟执行一次
    @Scheduled(cron = "0 */1 * * * ?")
    public void test1() {
        // your code
    }

    @Scheduled(fixedDelay = 5000)
    public void test2() {
        // your code
    }
    /**
     * 每个10分的延后3分执行
     * spring 的 cron 和 linux 的 cron 相比,好像spring多了第一位是秒
     */
    @Scheduled(cron = "0 3/10 * * * ?")
    public void test3() {
        // your code
    }

    /**
     * 每天凌晨1:04触发
     */
    @Scheduled(cron = "0 4 1 ? * *")
    public void test4() {
        // your code
    }


}

里面的方法,就会根据Scheduled定义的规则排程执行了,关于cron详细解释,可以查看:

https://blog.terrynow.com/2021/07/10/java-spring-springboot-schedule-implement/

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论