当前位置 博文首页 > Jqcode:简单记录Spring中轻量级任务调度@Scheduled注解的使用

    Jqcode:简单记录Spring中轻量级任务调度@Scheduled注解的使用

    作者:[db:作者] 时间:2021-09-16 10:32

    提到定时任务调度,可能第一时间会想到quartZ框架,但是在Spring3.0以后支持@Scheduled注解实现任务调度,它相当于一个轻量级的quartZ框架,简单配置易上手,以注解的形式注入spring ioc实现任务调度。????1è£é???1??????1????¢???¤′??_è£é?_???_???¤′è?¨?

    ?

    第一步,Spring配置文件,applicationContext.xml文件配置。

    增加配置文件的命名空间

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

    在xsi:schemaLocation中加入

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

    开启定时任务并配置任务注解包扫描路径(包路径写自己的定时任务类所在包路径)

    <!--开启定时任务-->
    <task:annotation-driven/>
    <!--定时任务扫描包路径-->
    <context:component-scan base-package="com.zhicall.pay.message.service" />

    以上配置完毕,可以敲代码了。?ˉ???é???_?é?è?¨?

    第二步,使用@Scheduled注解。

    @Component
    public class ScheduledTest {
    
        @Scheduled(cron = "0 0/1 * * * ? ")     // 每1分钟执行一次
        public void test(){
            System.out.println("执行成功!");
        }
        
    }

    输出结果,略。

    注意,@Scheduled注解在方法上,@Component注解在类上,方法返回值类型必须为void。

    ?????????°?-¤??????±???????????_???_?°?-¤???_???è?¨?

    cs