4.1 introduction to quartz
Quartz is an open source project in the field of Job scheduling. Quartz can be used alone or integrated with the spring framework. The latter is generally used in actual development. Using quartz, you can develop one or more scheduled tasks. Each scheduled task can be executed separately, such as every 1 hour, at 10 a.m. on the first day of each month, at 5 p.m. on the last day of each month, etc.
Official website: http://www.quartz-scheduler.org/
maven coordinates:
<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>
4.2 introduction to quartz
This case is based on the integration of Quartz and spring. Specific steps:
(1) Create the maven project quartzdemo, import the coordinates related to Quartz and spring, POM The XML file is as follows
<?xml version="1.0" encoding="UTF-8"?> <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"> <modelVersion>4.0.0</modelVersion> <groupId>com.itheima</groupId> <artifactId>quartdemo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.2.RELEASE</version> </dependency> <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> </project>
(2) Customize a Job
package com.itheima.jobs; /** * Custom Job */ public class JobDemo { public void run(){ System.out.println("job execute..."); } }
(3) Provide Spring configuration file Spring jobs XML to configure custom Job, task description, trigger, scheduling factory, etc
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Register custom Job --> <bean id="jobDemo" class="com.itheima.jobs.JobDemo"></bean> <!-- register JobDetail,The function is responsible for calling the specified through reflection Job --> <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- Injection target object --> <property name="targetObject" ref="jobDemo"/> <!-- Injection target method --> <property name="targetMethod" value="run"/> </bean> <!-- Register a trigger and specify the time when the task is triggered --> <bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <!-- injection JobDetail --> <property name="jobDetail" ref="jobDetail"/> <!-- Specifies the time to trigger, based on Cron expression --> <property name="cronExpression"> <value>0/10 * * * * ?</value> </property> </bean> <!-- Register a unified scheduling factory to schedule tasks through this scheduling factory --> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <!-- Inject multiple triggers --> <property name="triggers"> <list> <ref bean="myTrigger"/> </list> </property> </bean> </beans>
(4) Write the main method to test
package com.itheima.jobs.com.itheima.app; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { new ClassPathXmlApplicationContext("spring-jobs.xml"); } }
Execute the above main method and observe the console. It can be found that the output occurs every 10 seconds, indicating that the custom Job is called every 10 seconds.
4.3 cron expression
In the above introductory case, we specified an expression: 0 / 10 * *?
This expression is called cron expression, which can flexibly define the execution time of the program that meets the requirements. In this section, let's learn how to use cron expressions. As shown below:
The cron expression is divided into seven fields separated by spaces. The last field (year) can be empty. Each field has its own allowed values and some special characters. Using these special characters can make the expressions we define more flexible.
The following is an introduction to these special characters:
Comma (,): specifies a list of values. For example, in the month field, 1,4,5,7 represents January, April, may and July
Horizontal bar (-): specify a range. For example, in the time domain, 3-6 represents 3 points to 6 points (i.e. 3 points, 4 points, 5 points and 6 points)
Asterisk (*): indicates that this field contains all legal values. For example, using an asterisk in the month field means that it is triggered every month
Slash (/): indicates increment. For example, 0 / 15 in the second field indicates every 15 seconds
Question mark (?): It can only be used in the day and week fields, but it cannot be used in both fields at the same time. Indicates no assignment
Pound sign (#): it can only be used in the week field to specify the day of the week in the month, for example 6#3, which means the third Friday of a month (6 = Friday, 3 means the third week in the month)
50: The last value allowed on a field. Can only be used on day and week fields. When used in the day field, it represents the last day of the month specified in the month field. When used in the week field, it indicates that the last day of the week is Saturday
W: The w character represents the working day (Monday to Friday). It can only be used in the day field. It is used to specify the nearest working day from the specified day
4.4 cron expression online generator
We introduced cron expressions earlier, but there are still some difficulties in writing their own expressions. We can use some cron expression online generators to generate expressions according to our needs.
5. Regularly clean up garbage pictures
Previously, we have completed the management of the physical examination package. When adding the package, the basic information and pictures of the package are submitted to the background for operation in two times. That is, the user first uploads the picture to the qiniu cloud server, and then submits other information entered in the new window. If the user just uploads the picture without submitting other information entered, the picture will become a garbage picture because its existence is not recorded in the database. At this time, how do we deal with these garbage pictures?
The solution is to clean up these garbage pictures regularly through the scheduled task component. In order to distinguish which pictures are junk pictures, we save the pictures to a redis set after the file is uploaded successfully. When the package data is inserted into the database, we save the picture name to another redis set. We can obtain the names of all junk pictures by calculating the difference between the two sets.
In this chapter, we will find out all the junk images by calculating the difference between the two sets of redis based on the Quartz timing task, and then we can clean up the junk images.
Operation steps:
(1) Create maven project health_jobs. The packaging method is war. Import Quartz and other related coordinates
....... slightly
(6) Create ClearImgJob scheduled task class
package com.itheima.jobs; import com.itheima.constant.RedisConstant; import com.itheima.utils.QiniuUtils; import org.springframework.beans.factory.annotation.Autowired; import redis.clients.jedis.JedisPool; import java.util.Set; /** * Customize the Job to clean up garbage pictures regularly */ public class ClearImgJob { @Autowired private JedisPool jedisPool; public void clearImg(){ //Calculate the difference between the two sets saved in Redis to obtain the garbage picture name set Set<String> set = jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES); if(set != null){ for (String picName : set) { //Delete the picture on qiniu ECS QiniuUtils.deleteFileFromQiniu(picName); //Delete picture name from Redis collection jedisPool.getResource(). srem(RedisConstant.SETMEAL_PIC_RESOURCES,picName); } } } }