定時任務技術

破忒头头發表於2024-03-14

SpringBoot整合Quartz

匯入pom檔案

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

QuartzConfig

package com.pickle.config;

import com.pickle.quartz.MyQuartz;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Pickle
 * @version V1.0
 * @date 2024/3/14 11:42
 */
@Configuration
public class QuartzConfig {
    /**
     * 定義具體的工作明細
     * @return
     */
    @Bean
    public JobDetail printJobDetail(){
        //繫結具體的工作
        return JobBuilder.newJob(MyQuartz.class).storeDurably().build();
    }

    /**
     * 觸發器
     * 繫結對應的工作明細
     * @return
     */
    @Bean
    public Trigger printTrigger(){
        //日期和星期一般不會同時規定
        //ToDo:cron表示式
        ScheduleBuilder<CronTrigger> scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        return TriggerBuilder.newTrigger().forJob(printJobDetail()).withSchedule(scheduleBuilder).build();
    }

}

Spring簡化Quartz

新增註解

編寫任務

package com.pickle.demo;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author Pickle
 * @version V1.0
 * @date 2024/3/14 11:57
 */
@Component
public class MyBean {
    @Scheduled(cron = "0/1 * * * * ?")
    public void  print(){
        System.out.println("Quartz task on..");
    }
}

相關文章