---
# System prepended metadata

title: '[Java]Springboot定時任務'

---

# [Java]Springboot定時任務

某些情況我們需要透過程式來幫助我們在固定的時間自動執行程式，這時候能透過定時任務來幫忙完成。

## Scheduled
首先一定要記得放上 @Component，Spring 才會把這個 class 註冊為 Bean，並且在 SpringApplication.run 的類別加上@EnableScheduling 才會啟用

透過註解 @Scheduled 搭配 [cron表達式](https://matthung0807.blogspot.com/2020/12/quartz-cron-expressions-format.html)來完成
這裡是指每3秒執行一次任務
![](https://i.imgur.com/CKtVv6K.png)

執行結果:
![](https://i.imgur.com/6qcZ3UB.png)


## 整合Quartz
*  Job
*  Trigger
*  Scheduler
 
首先先創建MyJob.java和QuartzMain.java

### MyJob.java
```
package com.example.quartz;


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("任務被執行:"+ new Date());
    }
}
```

### QuartzMain.java
```
package com.example.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzMain {
    public static void main(String[] args) throws Exception {
        // 創建Job對象
        JobDetail job = JobBuilder.newJob(MyJob.class).build();
        // 創建Trigger對象
        /*
            1.簡單trigger 簡單的重複
            2.cron trigger 依照cron表達式
         */

        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever()).build();

        //創建 scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(job,trigger);

        //啟動scheduler
        scheduler.start();

    }
}
```
### 測試結果

![](https://i.imgur.com/LimYAm4.png)

### 使用Cron trigger

```
package com.example.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzMain {
    public static void main(String[] args) throws Exception {
        // 創建Job對象
        JobDetail job = JobBuilder.newJob(MyJob.class).build();
        // 創建Trigger對象
        /*
            1.簡單trigger 簡單的重複
            2.cron trigger 依照cron表達式
         */

//        Trigger trigger = TriggerBuilder
//                .newTrigger()
//                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever()).build();
        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build();

        //創建 scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(job,trigger);

        //啟動scheduler
        scheduler.start();

    }
}
```
### 測試結果

![](https://i.imgur.com/dzHCtzY.png)
