Java實現定時任務的方法總結
補充:cron表達式
秒 分 時 日期 月份 星期
如果日期有則星期為?
如果星期有則日期為?
基本知識
調度器 Scheduler : 運行到觸發(fā)時間點
觸發(fā)器 Trigger : 到達某一時間點后觸發(fā)鬧鐘
執(zhí)行器 Executors : 觸發(fā)鬧鐘后執(zhí)行響聲
方式一:使用sleep方法
無法指定時間
public class SleepDemo1 { public static void main(String[] args) { Runnable task = new Runnable(){ @Override public void run() { while (true){ System.out.println("hello"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(task); thread.start(); } }
方式二:JDK Timer和TimerTask
因為第一種的定時任務方法
java.util.Timer、java.util.TimerTask 非線程安全
每隔1秒執(zhí)行1次
public class TimerDemo2 { public static void main(String[] args) { TimerTask task = new TimerTask(){ @Override public void run() { System.out.println("hello"); } }; Timer timer = new Timer(); long delay = 1000; long interval = 2000; timer.schedule(task,delay,interval); } }
方式三:JDK ScheduledExecutorService
java.util.concurrent.ScheduledExecutorService
可以使用它創(chuàng)建和執(zhí)行定期執(zhí)行的任務,并且可以控制任務的執(zhí)行頻率。
使用Executors類的newScheduledThreadPool方法創(chuàng)建了一個ScheduledExecutorService對象,并使用該對象的scheduleAtFixedRate方法將任務安排在每隔1秒鐘執(zhí)行一次??梢愿鶕枰娜蝿盏膱?zhí)行頻率。
public class ScheduleExcutorsDemo3 { public static void main(String[] args) { ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); Runnable task = new Runnable(){ @Override public void run() { System.out.println("hello"); } }; scheduledExecutorService.scheduleAtFixedRate(task,0,1, TimeUnit.SECONDS); } }
方式四: Spring Task 中 的 @Scheduler
可以使用@Scheduled注解實現定時任務。該注解可以在Spring項目中使用,以在指定的時間間隔內自動調用指定方法。
每隔1秒鐘打印“hello timer”:
import org.springframework.scheduling.annotation.Scheduled; public class ScheduledAnnotationExample { @Scheduled(fixedRate = 1000) public void printMessage() { System.out.println("hello timer"); } }
方法五、Quartz框架
可以使用Quartz創(chuàng)建簡單的周期性任務,也可以創(chuàng)建復雜的作業(yè)調度,例如每周一次的作業(yè)
1、導入依賴
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
方式六:XXL-JOB
分布式任務調度平臺
下載代碼:https://gitee.com/xuxueli0323/xxl-job,通過git clone
將SQL運行到navcate中:doc/db/xxx.sql 找到克隆下來的項目中該目錄下的sql文件 Navicat創(chuàng)建相對應的數據庫
修改admin下的配置文件:郵箱、數據庫連接(jdbc:mysql://localhost:3306/xxl_job?serverTimeZone=Asia/Shanghai)
運行啟動類
訪問 http://localhost:8080/xxl-job-admin 默認賬戶admn,密碼123456
編寫一個自己的代碼
在頁面中添加定時任務并啟動運行
運行報錯:執(zhí)行器地址為空
打開頁面中的執(zhí)行器管理,新增一條
Appname在代碼中springboot項目配置文件下的appname,因為是自動注冊所以不用添加地址
注意:代碼不止需要運行admin的啟動類,兩個都需要運行
將xxl-job與springboot項目整合
1、將源代碼中的admin打包 clear - install 然后將jar包復制到自定義的文件夾中,在該文件夾的目錄下啟動
java -jar xxl-job-admin-2.4.1-SNAPSHOT.jar
訪問:http://localhost:8080/xxl-job-admin/
2、在項目中導入依賴
<dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> <version>2.2.0</version> </dependency>
3、將xxl-job-executor-sample-springboot這個模塊下的XxlJobConfig復制一份到springboot的項目中,然后將相關配置設置好即可(第4步 復制粘貼)
4、配置文件(使用application.properties才能正確不能用yml)
#xxljob定時任務 xxl.job.admin.addresses=http://192.168.129.1:8080/xxl-job-admin ### xxl-job, access token xxl.job.accessToken=default_token ### xxl-job executor appname xxl.job.executor.appname=xxl-job-executor-sample ### xxl-job executor registry-address: default use address to registry , otherwise use ip:port if address is null xxl.job.executor.address= ### xxl-job executor server-info xxl.job.executor.ip= xxl.job.executor.port=9999 ### xxl-job executor log-path xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler ### xxl-job executor log-retention-days xxl.job.executor.logretentiondays=30
5、編寫自己的定時任務
@Component public class MyTestHandler extends IJobHandler { @Override @XxlJob(value = "mytest1") public void execute() throws Exception { System.out.println("成功啦"); } }
6、在網頁中添加定時任務執(zhí)行器然后啟動
方式七:powerjob
相比于xxl-job更加的復雜,可以個性化,每一個appname達到了隔離
https://www.yuque.com/powerjob/guidence/bdvp1u#4DTFD
1、從github中下載項目
git clone https://github.com/PowerJob/PowerJob.git
2、創(chuàng)建一個數據庫(對比xxl-job來說更加的簡潔,只需要創(chuàng)建數據庫即可)
CREATE DATABASE IF NOT EXISTS powerjob-daily
DEFAULT CHARSET utf8mb4
3、修改配置文件中修改數據庫的配置
powerjob-server/powerjob-server-starter/application-daliy.properties
jdbc:mysql://localhost:3306/powerjob-daily?serverTimeZone=Asia/Shanghai
4、運行serve/starter下的主啟動類PowerJobServerApplication
如果運行不了,需要使用maven的clear以及install
5、打開頁面
http://localhost:7700/
6、注冊應用
填入powerjob-agent-test(需要與第七步中appname一致)和注冊密碼
7、編寫示例代碼
powerjob-worker-samples/application.properties修改app-name(與第六步一致)
8、編寫自己的代碼(建立一個新的類,繼承想要使用的處理器)然后運行主啟動類
各個處理器:https://www.yuque.com/powerjob/guidence/hczm7m
@Slf4j @Component public class TestHandler implements BasicProcessor { @Override public ProcessResult process(TaskContext context) throws Exception { // powerjob在線日志功能,使用該log可以直接在控制臺查看 OmsLogger omsLogger = context.getOmsLogger(); omsLogger.info("程序正在啟動,定時任務開啟:{}",context); return new ProcessResult(true,"成功"); } }
9、進入頁面創(chuàng)建任務
任務管理-新建任務
以上就是Java實現定時任務的方法總結的詳細內容,更多關于Java定時任務的資料請關注腳本之家其它相關文章!