一、Spring Job單機
Spring Job是一款基於Spring框架的多線程調度器,可以簡化項目中的定時任務等多線程操作,提高效率。與其他調度器不同,Spring Job支持分布式部署,能夠靈活處理任務分配。在單機模式下,我們可以直接使用Spring Job提供的註解來簡化定時任務的編寫。
首先,我們需要在項目中加入Spring Job的依賴包。在pom.xml文件中添加如下代碼:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
接下來,我們可以在需要定時執行的方法上添加@Scheduled註解,設置計劃執行時間。
@Scheduled(cron = "0/5 * * * * ?") public void job() { // 處理任務 }
在上面的代碼中,cron表達式代表每隔5秒執行一次job()方法。
二、Spring Job Scheduler連不上zk
當我們需要利用Spring Job進行分布式部署時,我們需要在調度器和執行器之間建立Zookeeper機制進行通信。但是,在實際使用過程中,有時會出現連不上Zookeeper的情況。這時,我們需要進行以下檢查:
1、確認Zookeeper地址和端口號是否正確
2、確認網絡是否正常,並且Zookeeper服務是否已經啟動
3、檢查Spring Job Scheduler的配置文件中是否正確配置了Zookeeper信息
quartz: scheduler: instanceName: clusterScheduler instanceId: AUTO jobStore: class: org.springframework.boot.autoconfigure.quartz.QuartzProperties$ClusteredJobStore properties: isClustered: true clusterCheckinInterval: 5000 misfireThreshold: 120000 cluster: checkinInterval: 20000 margin: 2 instanceId: AUTO instanceName: clusterJobStore threadPool: threadCount: 10
在上面的代碼片段中,我們可以看到配置了Zookeeper相關信息,並且使用了ClusteredJobStore作為Job存儲器,實現了分布式調度。
三、Spring Job Scheduler選取
Spring Job Scheduler提供了多種任務調度方式,我們可以根據不同情況選擇合適的調度方式。
1、@Scheduled註解
我們可以在需要定時執行的方法上添加@Scheduled註解,設置計劃執行時間。這種方式適用於簡單的定時任務。
2、Quartz調度器
Spring Boot默認使用Quartz作為任務調度器,Quartz提供了很多定時任務的配置選項,靈活性強,適用於複雜的定時任務需求。
3、TaskScheduler
TaskScheduler是Spring提供的接口,可以通過實現該接口,自定義定時任務調度器。這種方式適用於有特殊需求的定時任務。
四、完整代碼示例
下面是一個完整的Spring Job示例,實現了每隔5秒輸出一次”Hello World!”。
//pom.xml文件中添加依賴 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> //在Spring Boot啟動類上添加@EnableScheduling註解 @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } //創建定時任務 @Service public class JobService { @Scheduled(cron = "0/5 * * * * ?") public void job() { System.out.println("Hello World!"); } }
原創文章,作者:JLBE,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/138627.html