This is the fifth day of my participation in the August Wen Challenge.More challenges in August
Quartz is an open source job scheduling framework written entirely in Java. Don’t let the term job scheduling scare you, it’s not hard. Although the Quartz framework incorporates a lot of extra features, it’s almost unbearably easy to use for our purposes!
To put it simply, task scheduling is to do a specified task at a specified time. As mentioned earlier, you can use the native JDK, Timer and TimerTask to perform timed and fixed frequency jobs.
But what if we have some very demanding requirements? For example, send me an email on the second Sunday in May and the third Sunday in June.
How do you implement this seemingly random but somewhat regular scheduled task? Don’t worry, Quartz has it all covered for you!
Several conditions are necessary for us to execute tasks. One is the scheduler, the second is the task to execute, and the third is the trigger (which can be understood as setting the alarm clock). Linking together is where we use a scheduler to bind tasks and triggers to execute them at a specified point in time or in a loop.
Although the Quartz framework has over a dozen packages and over 300 classes, it is relatively easy to use.
First, we create a task, same thing we just implement the Job class, implement the specific method, and the task is created.
public class HelloJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
TimeUtil.printCurrentTime();
System.out.println("Hello world!");
}
}
Copy the code
The scheduler does not bind the Job implementation class HelloJob, but a JobDetail. Why do we need it?
We need to know the name of the task, the group or whatever, so that the typed logs can be distinguished. What Job is this Job detail bound to? We also have Class information. You might also need to pass parameters during the execution of the task, which is encapsulated in JobDetail.
The creation of JobDetail is even more subtle, and Quartz provides a builder style API for creating tasks and triggers. That’s how you create it.
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1").build();
Copy the code
Uh, uh, builder style… I don’t know, but it’s pretty easy to use, so we create a JobDetail, and we set HelloJob to bind, and we name and group the task, and we can still bind parameters. There’s no demo here.
The same creation style applies to triggers, so if you think about setting an alarm clock, we want to set the time to start executing, the frequency of executing, the number of times of executing, all at once, if your English is good enough, you should see all of these methods.
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group").
startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2)
.repeatForever())
.build();
Copy the code
Ah, is not good not according to the routine card, I want is the second Sunday in May every year to carry out ah, is not a fixed frequency ah, don’t worry, the back said.
Finally, create another scheduler using factory mode, StdSchedulerFactory is selected because this factory can load configuration files. We are provided with a set of configurations by default in the framework, which we can also create in the project root directory.
The scheduler creates, binds tasks and triggers to execution in a few lines of code.
SchedulerFactory sf = new StdSchedulerFactory(); Scheduler scheduler = sf.getScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start();Copy the code
Okay, so for that, we’ve done the coolest demo of a timed task. However, have you noticed that if you want to execute tasks at a fixed time and frequency, you can use Timer? Why bother the big brother?
Here’s the difference between Timer and Quartz.
1. Timer can only perform timed and fixed frequency tasks, while Quartz does not.
Timer has only one thread running, while Quartz has a thread pool and 10 threads are enabled by default.
3. There are anomalies in Timer, all GG, the accident scene cannot be recorded, while Quartz can.
Quartz wants flexible execution times. Who does it depend on? The scheduler? SimpleTrigger (SimpleTrigger) : SimpleTrigger (SimpleTrigger) : SimpleTrigger (SimpleTrigger) : SimpleTrigger
The other big implementation class is CronTrigger, which is calendar-based, so every day you can think of, it gives you a trigger, and it’s all about this time representation, and we use Cron expressions to represent the time of execution.
For example, “* * * * *? *” means every second, “0, 15, 10? 6L 2018-2020” shall be executed at 10:15 am on the last Friday of each month from 2018 to 2020. You think, WTF? I’m not going to go into the details of how to write this Cron expression, because you don’t need to write it yourself! In a nutshell, this is similar to regular expressions, and we can use online generation tools to generate them.
You just need to search for the Cron expression online generator.
Now that we have the arbitrary time, we can use CronTrigger to define triggers, the core of which is the Cron expression.
CronTrigger cronTrigger = (CronTrigger)TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group")
.startNow()
.withSchedule(CronScheduleBuilder
.cronSchedule("* * * * * ? *"))
.build();
Copy the code
As for multi-threading and persistence-related classes, they are all in the scheduler. It has to be said that Quartz encapsulates well, and users do not feel these at all. Inside StdSchedulerFactory, the core scheduler QuartzScheduler is encapsulated. JobStore for persistent tasks, multithreaded thread pool, thread executor.
But I don’t dive into it without a specific business need, and let’s not forget that Quartz is configurable, which I can do without a business scenario.
That’s how you get to know Quartz. You can play it yourself. But if you don’t know Timer, that’s your problem. I’ll show you next time
PS. It doesn’t matter, you can like, comment and retweet like crazy.