We often need scheduled tasks in development, such as regularly updating some information to organize, delete and other operations in documents. These situations can be implemented using @Scheduled scheduled tasks, but once the service is started, it cannot be modified (it is scheduled on the interface) Task)
Then we need to deploy a dynamic scheduled task system management of quartz to realize the operation of tasks and information.
The core of quartz’s dynamic scheduled tasks is to write the task, configure the trigger, and then use the scheduling factory to schedule the task
plus dependencies
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency>
First implement a simple function as follows:
Implementation lasts for one month, printing information at 0 o’clock every day, writing task information first
class MyJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { //Write the task logic to be executed here System.out.println("New day"); // If you need to stop the task after one month, you can check the time here and call the scheduler's shutdown method to stop the scheduler if (isOneMonthElapsed()) { try { Scheduler scheduler = jobExecutionContext.getScheduler(); scheduler.shutdown(true); // true means waiting for the current task to complete before shutting down } catch (SchedulerException e) { e.printStackTrace(); } } } // Determine whether a month has passed private boolean isOneMonthElapsed() { // Here we determine whether a month has passed based on business logic // You can customize the logic as needed return false; // This example returns false, you need to implement your own logic } }
After that comes the configuration
public class MyScheduler { public static void main(String[] args) throws SchedulerException { //Create a scheduler factory SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); // Start scheduler scheduler.start(); //Create a JobDetail and define the tasks to be performed JobDetail jobDetail = JobBuilder.newJob(MyJob.class) .withIdentity("myJob", "group1") .build(); // Create a trigger that fires at 0 o'clock every day Calendar startTime = Calendar.getInstance(); startTime.set(Calendar.HOUR_OF_DAY, 0); startTime.set(Calendar.MINUTE, 0); startTime.set(Calendar.SECOND, 0); startTime.set(Calendar.MILLISECOND, 0); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("dailyTrigger", "group1") .startAt(startTime.getTime()) // Define the task start time .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInHours(24) // Execute every 24 hours .repeatForever()) // Repeatedly .endAt(getEndTime()) // The end time is one month later .build(); //Register tasks and triggers to the scheduler scheduler.scheduleJob(jobDetail, trigger); } // Get the time one month later private static Date getEndTime() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); //Add one month return calendar.getTime(); } }
Next I will explain the functions of various objects
Job: There is only one execute to implement this abstract class. The parameter is Scheduling. When executing, the scheduler object will be passed in for shutdown, etc.
As shown below
Internally there is some logic that requires timing
At this point the task object is created.
The next step is to use quartz’s scheduling to implement dynamic timing execution of this task.
//Create scheduler factory SchedulerFactory schedulerFactory = new StdSchedulerFactory(); //Create scheduler Scheduler scheduler = schedulerFactory.getScheduler();
Create a scheduler factory as follows
Use the JobBuilder constructor to construct a JobDetail object based on MyJob’s own scheduled task class
Why not use MyJob directly for scheduling? JobBuilder will create an object for scheduling every time. It is not a singleton and will not cause thread safety issues
Remember to set the task name and group in the withIdentity function
Then create a trigger
The trigger core has four parameters
Start time startAt(startTime.getTime()) End time endAt(getEndTime()) The number of repetitions repeatForever() is repeated until the end time Repeat interval withIntervalInHours(24)
Note that the two parameters withIdentity have nothing to do with the above.
After successful creation, bind the scheduler
In this way, the scheduler is successfully bound.
Explanation on starting and shutting down the scheduler
scheduler.start() This method is used to start the Quartz scheduler and let it start executing scheduled tasks. Once the scheduler is started, it will execute tasks according to the defined triggers and jobs After the scheduler is started, you can add new jobs and triggers at any time, and it will continue to execute tasks according to the existing scheduling configuration. scheduler.shutdown() This method is used to close the Quartz scheduler and stop task execution. Calling scheduler.shutdown() will terminate the scheduler and release the resources it occupies, including thread pools, etc. Once the scheduler is closed, new tasks and triggers cannot be added, and a new scheduler object needs to be re-created. In your code, first call scheduler.start() to start the scheduler so that it can start executing tasks; then, use TimeUnit.MINUTES.sleep(1) to let the program sleep for one minute and wait for task execution; finally, call scheduler.shutdown () to close the scheduler and stop task execution; this is a typical usage that can control the life cycle of the scheduler If you want to restart the same scheduler later, you need to create a new scheduler object, reconfigure the job and triggers, and then call scheduler.start() again; note that a scheduler that has already called shutdown() cannot To start again, you need to create a new scheduler instance
In this way, a simple quartz dynamic timing task is implemented. For more detailed timing, please see chatGPT.
Implement a simple quartz system and quartz implement a dynamic task management system