自学内容网 自学内容网

Spring Task 调度任务

        Spring Task是调度任务框架,通过配置,程序可以按照约定的时间自动执行代码逻辑,基于注解方式实现需要如下注解:

  • @Component 任务调度类交给Spring IOC容器管理
  • @EnableScheduling 启用 Spring 的定时任务(Scheduling)功能
  • @Scheduled(cron="*/5 * * * * ?") 作用在方法上,方法按照约定的时间自动执行,通过CRON表达式配置约定时间

        cron表达式是一种用于设置定时任务的语法规则。它由6个字段组成,分别表示秒、分、时、日、月和星期几,每个字段可以设置为一个数字、一组数字(用逗号分隔)、一段数字范围(用短横线分隔)、通配符(表示任意值)或者特定的字符,示例如下:

  • "0 0 12 * * ?" 每天中午12点触发
  • "0 15 10 * * ?" 每天上午10:15触发
  • "0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
  • "0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发
  • "0 15 10 15 * ?" 每月15日上午10:15触发

        程序示例如下:

定时任务类:ScheduleTaskTest,系统每隔5秒钟执行一次test方法

package com.text.task;

import lombok.extern.java.Log;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Log
@Component
@EnableScheduling
public class ScheduleTaskTest {

    @Scheduled(cron="*/5 * * * * ?")
    public void test() {
        log.info("=======每隔5秒钟执行=======");
    }
}

测试类:

package com.text;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }
}

运行结果及结果分析:

        从运行结果可以看出,spring启动后,程序每隔5秒钟定时执行了test方法。

        注意:如果应用部署在集群环境,多个应用同时运行,会出现重复执行定时任务的情况,此种情况需要确保只有一个节点执行定时任务,项目上往往通过分布式锁来解决,集群中的每个节点都会尝试获取锁,只有获取锁的节点才能执行任务,其他节点则等待或跳过当前任务,具体实现方案后续再详细介绍。


原文地址:https://blog.csdn.net/xujinwei_gingko/article/details/142656384

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!