springboot+quartz implements scheduled tasks in a persistent manner
Jul 27, 2020 pm 06:33 PMThis article introduces springboot quartz to implement scheduled tasks in a persistent manner. The details are as follows:
It is long, and those who are patient can always get it. The final answer: This is my first time using quartz to do scheduled tasks. I apologize for any shortcomings.
First of all
It is relatively simple to do scheduled tasks in the springboot project. The simplest way to implement it is to use the **@Scheduled annotation. Then use @EnableScheduling** on the application startup class to enable scheduled tasks.
Example
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } // cron為每秒執(zhí)行一次 @Scheduled(cron = "* * * * * ?") public void print(){ System.out.println("執(zhí)行定時(shí)任務(wù)"); } }
ResultExecute scheduled tasksExecute scheduled tasks
Execute scheduled task
Execute scheduled task
Execute scheduled task
Execute scheduled task Task
Execute scheduled tasks
Execute scheduled tasks
Simple scheduled tasks can be done in this way, cron expression The result is the interval between task executions. However
In actual development, we may have many tasks, and we need to manually operate individual/all tasks, such as adding, opening , stop, continue and other operations. Then quartz will appear along with the BGM of "Qianniu Class B...".
quartzIntegration <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- Scheduler
- Start the trigger to execute the task
is used to define Job (task) trigger conditions, trigger time, trigger interval, termination time, etc.Task job
Specific task content to be performed
UseUse quartz requires a configuration file. The default configuration file quartz.properties can be found under the org.quartz package of the quartz jar package. quartz.properties
# 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.rmi.export: false org.quartz.scheduler.rmi.proxy: false org.quartz.scheduler.wrapJobExecutionInUserTransaction: false # 實(shí)例化ThreadPool時(shí),使用的線程類為SimpleThreadPool org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool # 線程總個(gè)數(shù) org.quartz.threadPool.threadCount: 10 # 線程的優(yōu)先級(jí) org.quartz.threadPool.threadPriority: 5 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true org.quartz.jobStore.misfireThreshold: 60000 # 持久化方式,默認(rèn)持久化在內(nèi)存中,后面我們使用db的方式 org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
Persistence of the quartz task to the db requires some officially defined databases Table, the sql file of the table can be found in the quartz jar package
coordinates org.quartz.impl.jdbcjobstore, you can see that there are many sql files in it, including various databases, we use MySQL, we There is no need to manually execute the sql statement, we will automatically initialize it later when starting the project.
Create our own properties file
# 實(shí)例化ThreadPool時(shí),使用的線程類為SimpleThreadPool org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool # threadCount和threadPriority將以setter的形式注入ThreadPool實(shí)例 # 并發(fā)個(gè)數(shù) org.quartz.threadPool.threadCount=10 # 優(yōu)先級(jí) org.quartz.threadPool.threadPriority=5 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true org.quartz.jobStore.misfireThreshold=5000 #持久化使用的類 org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX #數(shù)據(jù)庫(kù)中表的前綴 org.quartz.jobStore.tablePrefix=QRTZ_ #數(shù)據(jù)源命名 org.quartz.jobStore.dataSource=qzDS #qzDS 數(shù)據(jù)源,我們使用hikaricp,默認(rèn)的是c3p0 org.quartz.dataSource.qzDS.provider=hikaricp org.quartz.dataSource.qzDS.driver=com.mysql.cj.jdbc.Driver org.quartz.dataSource.qzDS.URL=jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 org.quartz.dataSource.qzDS.user=root org.quartz.dataSource.qzDS.password=123456 org.quartz.dataSource.qzDS.maxConnections=10
Since we are not using the default connection pool, let’s explore it and get the source code! Under this package: org.quartz.utils, there is a PoolingConnectionProvider. As the name suggests, the connection pool provider part source code
public interface PoolingConnectionProvider extends ConnectionProvider { /** The pooling provider. */ String POOLING_PROVIDER = "provider"; /** The c3p0 pooling provider. */ String POOLING_PROVIDER_C3P0 = "c3p0"; /** The Hikari pooling provider. */ String POOLING_PROVIDER_HIKARICP = "hikaricp"; }
Then HikariCpPoolingConnectionProvider class implements PoolingConnectionProvider, check it out yourself. We can search for c3p0 in StdSchedulerFactory under org.quartz.impl and find
if(poolingProvider != null && poolingProvider.equals(PoolingConnectionProvider.POOLING_PROVIDER_HIKARICP)) { cpClass = "org.quartz.utils.HikariCpPoolingConnectionProvider"; } else { cpClass = "org.quartz.utils.C3p0PoolingConnectionProvider"; }
Let’s take a look at the rest. Researching the initial source code is not as difficult or boring as imagined (I don’t like to read the source code either) ), but this source code does seem to have a small sense of accomplishment.
Go back to the topic channel and configure application.yml
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver password: 123456 url: jdbc:mysql://localhost:3306/quartz?characterEncoding=UTF8&useSSL=false&serverTimezone=GMT%2B8 username: root quartz: jdbc: initialize-schema: always job-store-type: jdbc
initialize-schema: always Every time you start the project, always initialize the database table and automatically create the key place of the table. The process is to delete the database table first. , create again, if the table does not exist, an exception will be thrown, but it will not affect the subsequent generated table. When the project is started next time, since the table already exists, the exception will not be thrown job-store-type: jdbc It is the task persistence type. When we use jdbc
, we may need to inject the spring object into the job. Without configuration, it cannot be injected.
/** * @author: taoym * @date: 2020/6/4 11:32 * @desc: 一定要自定義JobFactory重寫SpringBeanJobFactory的createJobInstance方法,否則在job中是獲取不到spring容器中的bean的 */ @Component public class JobFactory extends SpringBeanJobFactory { @Autowired private AutowireCapableBeanFactory beanFactory; /** * 這里覆蓋了super的createJobInstance方法,對(duì)其創(chuàng)建出來(lái)的類再進(jìn)行autowire */ @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object jobInstance = super.createJobInstance(bundle); beanFactory.autowireBean(jobInstance); return jobInstance; } }
Create quartz configuration file
@Configuration public class QuartzConfig { @Autowired private JobFactory jobFactory; /** * 讀取quartz.properties 文件 * 將值初始化 * * @return */ @Bean public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } @Bean public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setJobFactory(jobFactory); schedulerFactoryBean.setQuartzProperties(quartzProperties()); return schedulerFactoryBean; } /** * 初始化監(jiān)聽(tīng)器 * * @return */ @Bean public QuartzInitializerListener executorListener() { return new QuartzInitializerListener(); } @Bean(name = "scheduler") public Scheduler scheduler() throws IOException { return schedulerFactoryBean().getScheduler(); } }
Create trigger component
public class TriggerComponent { /** * @author: taoym * @date: 2020/6/1 10:35 * @desc: 構(gòu)建cron觸發(fā)器 */ public static Trigger cronTrigger(String cron) { CronTrigger cronTrigger = TriggerBuilder.newTrigger() .withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing()) .build(); return cronTrigger; } public static Trigger cronTrigger(String cron, JobDataMap jobDataMap) { CronTrigger cronTrigger = TriggerBuilder.newTrigger() .withSchedule(CronScheduleBuilder.cronSchedule(cron).withMisfireHandlingInstructionDoNothing()) .usingJobData(jobDataMap) .build(); return cronTrigger; } }
Just use this component to obtain the trigger.
Create Task
@DisallowConcurrentExecution public class TestJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { } }
jobExecutionContext Here you can get information such as task group, task name, trigger group, trigger name, jobdetail, etc. That annotation is to allow the same instance (jobdetail) to be executed only in a single thread. It can be understood that job is the interface, jobdetail is the implementation class, and a is one of the implementation classes. It takes 100s to perform a certain operation, and the timer you gave will perform an operation every 50s. When a is halfway through the execution Another thread needs to be started for execution. Using DisallowConcurrentExecution means that when a has not completed the operation, a is not allowed to open the thread and then perform the current operation. I don’t know if my description is easy to understand!
Create your own task list on demand. I use scheduled tasks to make crawlers (small crawlers)
CREATE TABLE `quartz_job` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '編號(hào)', `job_name` varchar(50) DEFAULT '' COMMENT '任務(wù)名', `job_group` varchar(50) DEFAULT '' COMMENT '任務(wù)組名稱', `job_desc` varchar(255) DEFAULT '' COMMENT 'job描述', `cron` varchar(50) DEFAULT '' COMMENT 'cron表達(dá)式', `status` tinyint(1) DEFAULT '0' COMMENT '狀態(tài)', `url` varchar(255) DEFAULT '' COMMENT '請(qǐng)求地址', `param` varchar(255) DEFAULT '' COMMENT '參數(shù)', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
When we add tasks, we don’t deal with quartz, just put the tasks in the database. . Don't panic, he will be useful later. This table needs to be added, deleted, modified and checked. We will query the task list in the system and select a single or all tasks to start executing
Execute tasks
@Resource private QuartzJobMapper quartzJobMapper; @Autowired private Scheduler scheduler; @Override public String start(Integer id) { JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(k,v); QuartzJob quartzJob = quartzJobMapper.selectByPrimaryKey(id); JobKey jobKey = JobKey.jobKey(quartzJob.getJobName(), quartzJob.getJobGroup()); jobDetail = JobBuilder.newJob(TestJob.class).withIdentity(jobKey).storeDurably().build(); Trigger trigger = TriggerComponent.cronTrigger(quartzJob.getCron(), jobDataMap); try { scheduler.scheduleJob(jobDetail, trigger); quartzJobMapper.updateStatus(true, id); return "開(kāi)始任務(wù)執(zhí)行成功"; } catch (SchedulerException se) { log.info("開(kāi)始任務(wù)的時(shí)候發(fā)生了錯(cuò)誤"); } return "開(kāi)始任務(wù)的時(shí)候發(fā)生了錯(cuò)誤,請(qǐng)檢查日志"; }
Finally, I pasted it according to the content of this tutorial Once the code is passed, it can run normally.
Recommended tutorial: "PHP"
The above is the detailed content of springboot+quartz implements scheduled tasks in a persistent manner. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. @Import introduces ordinary classes @Import introduces ordinary classes can help us define ordinary classes as Beans. @Import can be added to the classes corresponding to @SpringBootApplication (startup class), @Configuration (configuration class), and @Component (component class). Note: @RestController, @Service, and @Repository all belong to @Component@SpringBootApplication@Import(ImportBean.class)//ImportBean through the @Import annotation
