directory

Introduction:

Quartz Maven download dependencies

Quartz uses several objects and interfaces:

Here are some examples:

Job class

Perform class

conclusion

The Trigger class introduction

The syntax for using CronTrigger is introduced

Cron expression

Cron expression examples

This section describes the special characters of Cron expressions

Quartz. Properties Detailed version of the point

Configure the SQL download for the cluster database

Table is introduced

Pit mining records:

Unknown character set index for field ‘255’ received from server

The server time zone value ‘O ¹ U ± E ×¼ E ±¼ a’ is UNREC

 




 

Introduction:

In order to do regular tasks for the convenience of special look at spring quartz technology incidentally to make a summary for future use

 

Quartz Maven download dependencies

  • Maven’s website is repository.com/
  • Just use the latest package
  • Up to date:
<! -- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz --> <dependency> < the groupId > org. Quartz - the scheduler < / groupId > < artifactId > quartz < / artifactId > < version > 2.3.0 < / version > < / dependency >Copy the code

 

Quartz uses several objects and interfaces:

  • 1. A HelloJob implements Job (required)
public class HelloJob implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException {// Do the task here}}Copy the code
  • 2. Call JobDetail new job helloJob. Class (required)
JobDetail jobd = JobBuilder.newJob(HelloJob.class).withIdentity("job001").build();
Copy the code
  • 3. A Trigger class sets rules for triggering (mandatory)
CronTrigger trigger = (CronTrigger)TriggerBuilder.newTrigger() .withIdentity("trigger001", "group1") .withSchedule( CronScheduleBuilder.cronSchedule("0/2 * * * * ?" )) .build();Copy the code
  • 4. The last SchedulerFactory is used to initiate the call (required)
SchedulerFactory sfact = new StdSchedulerFactory();
		Scheduler scheduler = sfact.getScheduler();
		scheduler.start();
		scheduler.scheduleJob(jobd,trigger);
Copy the code
  • 5. There is also a configuration file called Quartz. Properties which can be set up by yourself or you can use the import package. If you need to configure the cluster, you can create a configuration file which can be automatically scanned, as long as it is in the project, don’t put the directory too deep (optional).
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#

org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.instanceid: AUTO
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false

org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

org.quartz.jobStore.misfireThreshold: 60000

org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
Copy the code

 

Here are some examples:

 

Job class

package com.superman.quartz; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; import org.quartz.Trigger; /** * @author yushen ** / public class HelloJob implements job {@override public void execute(JobExecutionContext context) throws JobExecutionException { Date d = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("now time:"+sf.format(d)); System.out.println("hello word! "); // Trigger CRT = context.gettrigger (); // System.out.println("start time:"+crt.getStartTime()); // System.out.println("start time:"+crt.getEndTime()); // JobKey jok = crt.getJobKey(); // System.out.println(jok.getGroup()+jok.getName()); // // Use jobexecutionContext to obtain key information. // JobKey key = context.getjobdetail ().getkey (); // // Obtain jobdetial key // system.out.println (key.getName()+":"+key.getGroup())); // // get the contents of trigger // TriggerKey trkey = context.gettrigger ().getkey (); // System.out.println("trggerkey"+trkey.getName()+trkey.getGroup()); // // // Obtain jobdetail data from context // JobDataMap datamap = context.getjobdetail ().getJobDatamap (); // JobDataMap tDatamap = context.gettrigger ().getJobDatamap (); // // System.out.println("---+----"+datamap.getFloat("FloatJobValue")); // System.out.println("---+----"+tdatamap.getDouble("DoubleTrggervalue")); / / / / / / / / / / for all data objects content JobDataMap ftdatamap = context. GetMergedJobDataMap (); // System.out.println("---+----"+ftdatamap.getDouble("DoubleTrggervalue")); / /}}Copy the code

 

Perform class

package com.superman.quartz; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class HelloScheduler { public static void main(String[] args) throws SchedulerException, InterruptedException { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // jobdetail jobd = jobBuilder.newJob (hellojob.class) //. WithIdentity ("job001", "group1").build(); JobDetail jobd = JobBuilder.newJob(HelloJob.class) .withIdentity("job001") // .usingJobData("message","hellomyjob001")// Add parameters //.usingJobData("FloatJobValue", 3.21f).build(); // System.out.println(jobd.getKey().getGroup()); // System.out.println(jobd.getKey().getName()); // System.out.println(jobd.getJobClass().getName()); // Date d = new Date(); // Date d2 = new Date(); // d.setTime(d.getTime()+3000); D2.settime (d2.getTime()+6000); // Trigger Trigger = TriggerBuilder //.newtrigger () //.withidentity ("trigger001", StartAt (d)// Set the start time. EndAt (d2)// Set the end time. UsingJobData ("message","hellomytrigger") UsingJobData (" DoubleTrggervalue ", 2.0 D) / /. StartNow () / /. WithSchedule (. / / SimpleScheduleBuilder simpleSchedule (). / / withIntervalInSeconds(2).repeatForever()) // .build(); // Date d = new Date(); // Date d2 = new Date(); // d.setTime(d.getTime()+4000); D2.settime (d2.getTime()+6000); // End time //SimpleTrigger time frequency // Execute every two seconds after 4 seconds from the current time //SimpleTrigger Trigger = (SimpleTrigger)TriggerBuilder // .newTrigger() // .withIdentity("trigger001", "Group1 ") //.startat (d)// start after 4 seconds // //. EndAt (d2)// End time takes precedence over other repeat flatness //.withSchedule(// SimpleScheduleBuilder // .simpleschedule (). // withIntervalInSeconds(2)//.withrepeatCount (3))// three times //.build(); // Cron expression second minute hour day month week year //1.2017 start at 10:15 every day //0 15 10? * * 2017 //2. Daily departure from 14:00 to 1459 level 1 18:00 to 1859, executed every 5 seconds //0/5 * 14,18 * *? // Once every Monday through Friday at 10:15 // once on the last day of every month at 10:15 // once on the third Friday of every month at 10:15 //L OR W can be used together // week fields are case-insensitive //cron expression online generator can be used CronTrigger Trigger = (CronTrigger) triggerBuilder.newtrigger () .withIdentity("trigger001", "group1") .withSchedule( CronScheduleBuilder .cronSchedule("0/2 * * * * ?") ) .build(); Date d0 = new Date(); Trigger and jobDetail SchedulerFactory sfact = new StdSchedulerFactory(); Scheduler scheduler = sfact.getScheduler(); scheduler.start(); System.out.println("----------now time:"+sf.format(d0)); scheduler.scheduleJob(jobd,trigger); // Scheduler suspends thread. sleep(3000) after two seconds; scheduler.standby(); Thread.sleep(5000); thread.sleep (5000); scheduler.start(); // start // scheduler.shutdown(); // Scheduler. Shutdown (true); }}Copy the code

 

conclusion

  • The first step is to create a xx agent class to implement the Job class interface
  • Implement the inherited method execute method
  • Write your own job task in a method
  • Associate the xx agent class with JobDetail in another class
  • The trigger class is used to set the rule, mode and time of job tasks
  • The scheduler method is used to start, close, restart, and pause

 

The Trigger class introduction

  • The trigger class contains the following common classes
  • Trigger // Common type
  • SimpleTrigger is based on frequency and so on
  • CronTrigger Is set based on time rules

The syntax for using CronTrigger is introduced

 

Cron expression

 

Cron expression examples

 

This section describes the special characters of Cron expressions

 

Quartz. Properties Detailed version of the point

# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
# ===========================================================================
# Configure Main Scheduler Properties 调度器属性
# ===========================================================================
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.instanceid:AUTO
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
# ===========================================================================  
# Configure ThreadPool 线程池属性  
# ===========================================================================
#线程池的实现类(一般使用SimpleThreadPool即可满足几乎所有用户的需求)
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
#指定线程数,至少为1(无默认值)(一般设置为1-100直接的整数合适)
org.quartz.threadPool.threadCount: 10
#设置线程的优先级(最大为java.lang.Thread.MAX_PRIORITY 10,最小为Thread.MIN_PRIORITY 1,默认为5)
org.quartz.threadPool.threadPriority: 5
#设置SimpleThreadPool的一些属性
#设置是否为守护线程
#org.quartz.threadpool.makethreadsdaemons = false
#org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
#org.quartz.threadpool.threadsinheritgroupofinitializingthread=false
#线程前缀默认值是:[Scheduler Name]_Worker
#org.quartz.threadpool.threadnameprefix=swhJobThead;
# 配置全局监听(TriggerListener,JobListener) 则应用程序可以接收和执行 预定的事件通知
# ===========================================================================
# Configuring a Global TriggerListener 配置全局的Trigger监听器
# MyTriggerListenerClass 类必须有一个无参数的构造函数,和 属性的set方法,目前2.2.x只支持原始数据类型的值(包括字符串)
# ===========================================================================
#org.quartz.triggerListener.NAME.class = com.swh.MyTriggerListenerClass
#org.quartz.triggerListener.NAME.propName = propValue
#org.quartz.triggerListener.NAME.prop2Name = prop2Value
# ===========================================================================
# Configuring a Global JobListener 配置全局的Job监听器
# MyJobListenerClass 类必须有一个无参数的构造函数,和 属性的set方法,目前2.2.x只支持原始数据类型的值(包括字符串)
# ===========================================================================
#org.quartz.jobListener.NAME.class = com.swh.MyJobListenerClass
#org.quartz.jobListener.NAME.propName = propValue
#org.quartz.jobListener.NAME.prop2Name = prop2Value
# ===========================================================================  
# Configure JobStore 存储调度信息(工作,触发器和日历等)
# ===========================================================================
# 信息保存时间 默认值60秒
org.quartz.jobStore.misfireThreshold: 60000
#保存job和Trigger的状态信息到内存中的类
org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
# ===========================================================================  
# Configure SchedulerPlugins 插件属性 配置
# ===========================================================================
# 自定义插件  
#org.quartz.plugin.NAME.class = com.swh.MyPluginClass
#org.quartz.plugin.NAME.propName = propValue
#org.quartz.plugin.NAME.prop2Name = prop2Value
#配置trigger执行历史日志(可以看到类的文档和参数列表)
org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingTriggerHistoryPlugin  
org.quartz.plugin.triggHistory.triggerFiredMessage = Trigger {1}.{0} fired job {6}.{5} at: {4, date, HH:mm:ss MM/dd/yyyy}  
org.quartz.plugin.triggHistory.triggerCompleteMessage = Trigger {1}.{0} completed firing job {6}.{5} at {4, date, HH:mm:ss MM/dd/yyyy} with resulting trigger instruction code: {9}  
#配置job调度插件  quartz_jobs(jobs and triggers内容)的XML文档  
#加载 Job 和 Trigger 信息的类   (1.8之前用:org.quartz.plugins.xml.JobInitializationPlugin)
org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
#指定存放调度器(Job 和 Trigger)信息的xml文件,默认是classpath下quartz_jobs.xml
org.quartz.plugin.jobInitializer.fileNames = my_quartz_job2.xml  
#org.quartz.plugin.jobInitializer.overWriteExistingJobs = false  
org.quartz.plugin.jobInitializer.failOnFileNotFound = true  
#自动扫描任务单并发现改动的时间间隔,单位为秒
org.quartz.plugin.jobInitializer.scanInterval = 10
#覆盖任务调度器中同名的jobDetail,避免只修改了CronExpression所造成的不能重新生效情况
org.quartz.plugin.jobInitializer.wrapInUserTransaction = false
# ===========================================================================  
# Sample configuration of ShutdownHookPlugin  ShutdownHookPlugin插件的配置样例
# ===========================================================================
#org.quartz.plugin.shutdownhook.class = \org.quartz.plugins.management.ShutdownHookPlugin
#org.quartz.plugin.shutdownhook.cleanShutdown = true
#
# Configure RMI Settings 远程服务调用配置
#
#如果你想quartz-scheduler出口本身通过RMI作为服务器,然后设置“出口”标志true(默认值为false)。
#org.quartz.scheduler.rmi.export = false
#主机上rmi注册表(默认值localhost)
#org.quartz.scheduler.rmi.registryhost = localhost
#注册监听端口号(默认值1099)
#org.quartz.scheduler.rmi.registryport = 1099
#创建rmi注册,false/never:如果你已经有一个在运行或不想进行创建注册
# true/as_needed:第一次尝试使用现有的注册,然后再回来进行创建
# always:先进行创建一个注册,然后再使用回来使用注册
#org.quartz.scheduler.rmi.createregistry = never
#Quartz Scheduler服务端端口,默认是随机分配RMI注册表
#org.quartz.scheduler.rmi.serverport = 1098
#true:链接远程服务调度(客户端),这个也要指定registryhost和registryport,默认为false
# 如果export和proxy同时指定为true,则export的设置将被忽略
#org.quartz.scheduler.rmi.proxy = false
Copy the code

 

 

  • Ok at this point you can use your own Quartz

 

Configure the SQL download for the cluster database

Download from www.quartz-scheduler.org/

  • Quartz-2.4.0-snapshot Decompress the download
  • This directory is the file address

 

Table is introduced

 

  • QRTZ_CALENDARS stores Quartz Calendar information as Blob
  • QRTZ_CRON_TRIGGERS stores Cron triggers, including Cron expressions and time zone information
  • QRTZ_FIRED_TRIGGERS Stores status information related to triggered triggers and the execution information of associated jobs
  • QRTZ_PAUSED_TRIGGER_GRPS stores information about the suspended Trigger group
  • QRTZ_SCHEDULER_STATE stores a small amount of Scheduler state information and other Scheduler instances (if used in a cluster)
  • QRTZ_LOCKS Stores information about the program’s non-watchable locks (if pessimistic locks are used)
  • QRTZ_JOB_DETAILS Stores the details of each configured Job
  • QRTZ_SIMPLE_TRIGGERS stores simple triggers, including repeats, intervals, and times touched
  • QRTZ_BLOG_TRIGGERS triggers are stored as a Blob type (for when Quartz users create their own custom Trigger type using JDBC and JobStore does not know how to store the instance)
  • QRTZ_TRIGGER_LISTENERS store information about configured TriggerListeners
  • QRTZ_TRIGGERS stores information about the configured Trigger

 

Pit mining records:

 

Unknown character set index for field ‘255’ received from server

Change the mysql version. The mysql version is high. The JAR version introduced in the project is low

 

The server time zone value ‘O ¹ U ± E ×¼ E ±¼ a’ is UNREC

C:\Users\yushen>mysql -u root -p Enter password: ****** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 4990 Server version: 8.0.15 MySQL Community Server - GPL Copyright (C) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help; ' or '\h' for help. Type '\c' to clear the current input statement. mysql> show variables like '%time_zne%'; Empty set, 1 warning (0.00 SEC) mysql> set global time_zone='+8:00'; Query OK, 0 rows affected (0.07 SEC) mysql> show variables like '%time_zne%'; Empty set, 1 warning (0.00 SEC) mysql>Copy the code

ok

 

Cluster code

  • Pure code and run run on eclipse: download.csdn.net/download/we…
  • Run on eclipse add code with packing: download.csdn.net/download/we…

 

Picture of Cluster Organization

 

Database table screenshot

  • These are the quartz table structures generated by running the Code in the Quartz. SQL file in the database itself

 

Present pom.xml and the code to open the jar package

The < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > com. Super < / groupId > < artifactId > SuperPortal < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < / parent > < artifactId > SupperPortal - Quartz < / artifactId > < properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < maven.com piler. Source > 1.8 < / maven.com piler source > < maven.com piler target > 1.8 < / maven.com piler. Target > < / properties > < dependencies > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> < artifactId > mysql connector - Java < / artifactId > < version > 8.0.15 < / version > < / dependency > <! Scheduler </groupId> <artifactId>quartz</artifactId> < version > 2.2.3 < / version > < / dependency > < the dependency > < groupId > org. Quartz - the scheduler < / groupId > < artifactId > quartz - Steve < / artifactId > < version > 2.2.3 < / version > < / dependency > < the dependency > < the groupId > org. Springframework < / groupId > < artifactId > spring - the context - support < / artifactId > < version > 3.2.3. RELEASE < / version > </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> <mainClass>${start-class}</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-5</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>com.superman.quartz.Quartz_Group_Application</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>assemble-all</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>Copy the code
  • If the same computer remembers to switch ports
  • Configure server 8086 in application.ymlh

 

The cluster is introduced

  • 1. Add data in SQL to the database
  • 2. Modify the Quartz configuration file: database location
  • 3. Start
  • 4. Call the create method in Controller
  • 5.ok

 

 

 

 

Blog homepage: blog.csdn.net/weixin_4274…

 

The article continues to update, forward to show the source, convenient update!