Quartz表達式生成地址:http://cron.qqe2.comjava
支持生成定時任務表達式和反解析,使用Quartz表達式的定時任務以下:git
/** * TODO 使用線程建立 job 定時任務 * @author 王鬆 */ public class JobThread { public static class Demo01 { static long count = 0; public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); count++; System.out.println(count); } catch (Exception e) { // TODO: handle exception } } } }; Thread thread = new Thread(runnable); thread.start(); } } }
/** * TODO 使用 TimerTask 建立job定時任務 * @author 王鬆 */ public class JobTimerTask { static long count = 0; public static void main(String[] args) { TimerTask timerTask = new TimerTask() { @Override public void run() { count++; System.out.println(count); } }; //建立timer對象設置間隔時間 Timer timer = new Timer(); // 間隔天數 long delay = 0; // 間隔毫秒數 long period = 1000; timer.scheduleAtFixedRate(timerTask, delay, period); } }
/** * TODO 使用線程池建立 job定時任務 * @author 王鬆 */ public class JobScheduledExecutorService { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); // 第二個參數爲首次執行的延時時間,第三個參數爲定時執行的間隔時間 service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS); } }
一、引入maven依賴github
<dependencies> <!-- quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency> </dependencies>
二、任務調度類web
public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("quartz MyJob date:" + System.currentTimeMillis()); } }
三、啓動類面試
public class JobQuartz { public static void main(String[] args) throws SchedulerException { //1.建立Scheduler的工廠 SchedulerFactory sf = new StdSchedulerFactory(); //2.從工廠中獲取調度器實例 Scheduler scheduler = sf.getScheduler(); //3.建立JobDetail, JobDetail jb = JobBuilder.newJob(MyJob.class) //job的描述 .withDescription("this is a ram job") //job 的name和group .withIdentity("ramJob", "ramGroup") .build(); //任務運行的時間,SimpleSchedle類型觸發器有效,3秒後啓動任務 long time= System.currentTimeMillis() + 3*1000L; Date statTime = new Date(time); //4.建立Trigger //使用SimpleScheduleBuilder或者CronScheduleBuilder Trigger t = TriggerBuilder.newTrigger() .withDescription("") .withIdentity("ramTrigger", "ramTriggerGroup") //.withSchedule(SimpleScheduleBuilder.simpleSchedule()) //默認當前時間啓動 .startAt(statTime) //兩秒執行一次,Quartz表達式,支持各類牛逼表達式 .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) .build(); //5.註冊任務和定時器 scheduler.scheduleJob(jb, t); //6.啓動 調度器 scheduler.start(); }
@Component @Configuration //1.主要用於標記配置類,兼備Component的效果。 @EnableScheduling // 2.開啓定時任務 public class SaticScheduleTask { @Scheduled(cron = "0/5 * * * * ?") //3.添加定時任務 //@Scheduled(fixedRate=5000) //或直接指定時間間隔,例如:5秒 private void configureTasks() { System.err.println("執行靜態定時任務時間: " + LocalDateTime.now()); } }
xxl-job 有什麼用?spring
Spring Boot 基礎教程就不介紹了,推薦看這裏:https://github.com/javastacks...sql
第一步: github下載源碼導入數據庫
下載地址:https://github.com/xuxueli/xx...tomcat
當前版本目錄結構 2.1.1springboot
第二步: 執行sql
文件地址:xxl-job/doc/db/tables_xxl_job.sql
當前2.1.1版本sql
第三步: 修改xxl-job-admin項目配置
配置文件:application.properties
修改數據庫鏈接
第四步: 啓動admin項目
springboot 方式啓動項目
訪問 http://localhost:8080/xxl-job-admin/
帳號密碼:admin / 123456
任務調度中心就搭建好了
接下來須要建立一個服務器鏈接任務調度中心
建立一個 boot 項目
個人目錄結構
pom.xml
web核心及 xxl-job-core
<!-- spring-boot-starter-web (spring-webmvc + tomcat) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- xxl-job-core 版本號根據本身下載的版本修改 --> <dependency> <groupId>com.xuxueli</groupId> <artifactId>xxl-job-core</artifactId> <version>2.1.1-SNAPSHOT</version> </dependency>
logback.xml
日誌配置直接拷貝
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="false" scan="true" scanPeriod="1 seconds"> <contextName>logback</contextName> <property name="log.path" value="/data/applogs/xxl-job/xxl-job-executor-sample-springboot.log"/> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.path}</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern> </rollingPolicy> <encoder> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n </pattern> </encoder> </appender> <root level="info"> <appender-ref ref="console"/> <appender-ref ref="file"/> </root> </configuration>
application.properties 加入配置
需修改或自定義
# 端口號 server.port=8081 # 日誌 logging.config=classpath:logback.xml ## xxl-job admin 地址,多個逗號分隔" xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin ## xxl-job名稱 || socket ip 當前項目部署的ip地址/本機ip || socket 端口號 xxl.job.executor.appname=xxl-job-executor-sample xxl.job.executor.ip=192.168.43.153 xxl.job.executor.port=9999 ## xxl-job, access token xxl.job.accessToken= ## xxl-job log path xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler ## xxl-job log retention days xxl.job.executor.logretentiondays=-1
添加boot配置類 XxlJobConfig
/** * xxl-job xxljob.config */ @SuppressWarnings("ALL") @Configuration public class XxlJobConfig { private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class); @Value("${xxl.job.admin.addresses}") private String adminAddresses; @Value("${xxl.job.executor.appname}") private String appName; @Value("${xxl.job.executor.ip}") private String ip; @Value("${xxl.job.executor.port}") private int port; @Value("${xxl.job.accessToken}") private String accessToken; @Value("${xxl.job.executor.logpath}") private String logPath; @Value("${xxl.job.executor.logretentiondays}") private int logRetentionDays; @Bean(initMethod = "start", destroyMethod = "destroy") public XxlJobSpringExecutor xxlJobExecutor() { logger.info(">>>>>>>>>>> xxl-job xxljob.config init."); XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor(); xxlJobSpringExecutor.setAdminAddresses(adminAddresses); xxlJobSpringExecutor.setAppName(appName); xxlJobSpringExecutor.setIp(ip); xxlJobSpringExecutor.setPort(port); xxlJobSpringExecutor.setAccessToken(accessToken); xxlJobSpringExecutor.setLogPath(logPath); xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays); System.err.println(ip+":"+port); return xxlJobSpringExecutor; } /** * 針對多網卡、容器內部署等狀況,可藉助 "spring-cloud-commons" 提供的 "InetUtils" 組件靈活定製註冊IP; * * 一、引入依賴: * <dependency> * <groupId>org.springframework.cloud</groupId> * <artifactId>spring-cloud-commons</artifactId> * <version>${version}</version> * </dependency> * * 二、配置文件,或者容器啓動變量 * spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.' * * 三、獲取IP * String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); */ }
任務job
@JobHandler(value="demoJobHandler") @Component public class DemoJobHandler extends IJobHandler { static int count; @Override public ReturnT<String> execute(String param) throws Exception { System.out.println("執行job任務"+count++); return SUCCESS; } }
admin 後臺配置
執行管理器下
任務管理下編輯任務
定時規則生成:http://cron.qqe2.com/
job任務名:@JobHandler註解值 >> 如:@JobHandler(value=「demoJobHandler」)
啓動
這樣就配置完成了
原文連接:https://blog.csdn.net/qq_4146...
版權聲明:本文爲CSDN博主「兮家小二」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連接及本聲明。
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2021最新版)
2.終於靠開源項目弄到 IntelliJ IDEA 激活碼了,真香!
3.阿里 Mock 工具正式開源,幹掉市面上全部 Mock 工具!
4.Spring Cloud 2020.0.0 正式發佈,全新顛覆性版本!
以爲不錯,別忘了隨手點贊+轉發哦!