Timer 1

1. Traditional timer

1.1 Timer

1. After the implementation of the program to 10 seconds

Timer timer = new Timer();
timer.schedule(new TimerTask() {
	@Override
	public void run() {
		System.out.println("开始打印。。。");
	}
}, 10000);

2. After the implementation of the program to 10 seconds, three seconds and then did not perform a

Timer timer = new Timer();
timer.schedule(new TimerTask() {
	@Override
	public void run() {
		System.out.println("开始打印。。。");
	}
}, 10000,3000);

 

1.2 TimerTask

1. Let a timer 2 seconds 4 seconds and then performs execution, followed by two seconds and then perform performed at 4 seconds, and so forth

Custom TimerTask

package com.bjc.thread.demo2;

import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask{
	private static Integer count = 0;
	@Override
	public void run() {
		count = (count + 1) % 2;
		System.out.println("乓!");
		new Timer().schedule(new MyTimerTask(), 2000 + 2000 * count);
	}

}

transfer

package com.bjc.thread.demo2;

import java.util.Date;
import java.util.Timer;

public class TranditionalTimer {
	public static void main(String[] args) throws InterruptedException {
		Timer timer = new Timer();
		timer.schedule(new MyTimerTask(), 2000);
		
		while(true){
			System.out.println(new Date().getSeconds());
			Thread.sleep(1000);
		}
	}
}

Results of the:

2. Timing frame Quartz

2.1 Introduction

        Quartz is a task scheduling framework for java-based implementation, for the execution of any task you want to perform.

        Quartz is OpenSymphony the open source community and an open source project in Job scheduling field, is entirely java development of an open source job scheduling system, "Task Progress Manager" is one of the pre-determined time (to be included in the agenda) time to reach responsible execution system (or notice) other software components.
Quartz with a small Java library distribution file (.jar file), the Quartz library file contains all the core functionality. The main features of these interfaces (API) is Scheduler interface. It provides simple operation, such as: the task into the schedule or cancel the schedule, the start / stop / pause schedule progress.

        The official website is http://www.quartz-scheduler.org

2.2 Quartz runtime environment

1. Quartz can be embedded in another run stand-alone application

2. Quartz may be instantiated within an application server (or servlet container), and is involved in the transaction

3. Quartz can be used as a standalone program (its own java virtual machine), you can use the RMI

4. Quartz can be instantiated, as a separate item cluster (load balancing and failover features), for execution of the job.

2.3 Quartz Core Concepts

2.3.1 Task Job

        Job class is the task that you want to achieve, each job must implement org.quartz.job interfaces, and only need to implement the execute () method defined by the interface.

2.3.2 Trigger Trigger

        Trigger trigger for you to perform a task, for example, you want to send a timed 3:00 daily statistics e-mail, Trigger will be set 3:00 to carry out the task, Trigger mainly include two SimpleTrigger and CronTrigger two kinds.

2.3.3 Scheduler Scheduler

        Scheduler is a task scheduler, it will trigger Trigger task job and integrate responsible to perform the job Trigger set time based on

2.4 Getting Case

2.4.1 development environment ready

Create a new maven project quartzDemo

2.4.2 Add dependence

Add quartz-dependent

In the warehouse https://www.mvnrepository.com , search for quartz, quartz and find Quartz Jobs dependent, then pom.xml file, add dependencies tag in the tag, add into the quartz dependence

<dependency>
	<groupId>org.quartz-scheduler</groupId>
	<artifactId>quartz</artifactId>
	<version>2.3.0</version>
</dependency>
	
<dependency>
	<groupId>org.quartz-scheduler</groupId>
	<artifactId>quartz-jobs</artifactId>
	<version>2.3.0</version>
</dependency>

After adding the view-dependent jar under the Maven Dependencies, we found under which slf4j interface jar package, so we need to add log rely jar

Right --maven - add Dependence, input slf4, FIG.

In the same step, the input log4j

Finally, add the log4j configuration file

2.4.3 Changing compiler environment

After the addition is complete dependence, we found that 1.5 compiler environment, we want it to be 1.8, this time you can add maven plugin

Right --maven - add plugin, enter maven-compile

Then, in pom.xml, add the following configuration corresponding to the tag compile version of the plug-in configuration

<configuration>
    <target>1.8</target>
    <source>1.8</source>
</configuration>

Complete pom.xml as follows:

<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>cn.bjc</groupId>
  <artifactId>quartzDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <!-- 添加依赖 -->
  <dependencies>
  	<dependency>
	    <groupId>org.quartz-scheduler</groupId>
	    <artifactId>quartz</artifactId>
	    <version>2.3.0</version>
	</dependency>
	
	<dependency>
	    <groupId>org.quartz-scheduler</groupId>
	    <artifactId>quartz-jobs</artifactId>
	    <version>2.3.0</version>
	</dependency>
	
	<!-- quartz依赖日志接口slf4j-api-1.7.7.jar ,所以也需要log4j-->
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-log4j12</artifactId>
		<version>1.7.12</version>
	</dependency>
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	</dependency>
  </dependencies>
  
  <build>
  	<plugins>
  		<plugin>
  			<groupId>org.apache.maven.plugins</groupId>
  			<artifactId>maven-compiler-plugin</artifactId>
  			<version>3.5.1</version>
  			<configuration>
  				<target>1.8</target>
  				<source>1.8</source>
  			</configuration>
  		</plugin>
  	</plugins>
  </build>
</project>

2.4.4 Case Code

1. Create Job category

job class needs to implement Job

package cn.bjc.quartz.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job {

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		Calendar calendar = Calendar.getInstance();
		Date time = calendar.getTime();
		String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
		System.out.println("任务开始执行,时间是:" + format);
	}

}

2. Create a new main perform scheduling class

Divided into three steps:

1. The scheduler (Scheduler), obtained from the factory in StdSchedulerFactory

Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

注意:这个默认的调度器内部其实是返回new StdSchedulerFactory()

2. 任务实例(JobDetail),通过JobBuilder创建

3. 触发器(Trigger)

代码:

package cn.bjc.quartz.main;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import cn.bjc.quartz.job.HelloJob;

public class HelloSchedulerDemo {

	public static void main(String[] args) throws Exception {
		// 1. 调度器(Scheduler),从工厂获取
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // 内部默认是new StdSchedulerFactory()
		// 2. 任务实例(JobDetail),通过JobBuilder创建
		JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)	// 加载任务类,与HelloJob绑定
							.withIdentity("job1", "group1")	// 参数一:任务的名称(唯一实例);参数二:任务组的名称,对任务进行分组
							.build();
		// 3. 触发器(Trigger)
		Trigger trigger = TriggerBuilder.newTrigger()
							.withIdentity("trigger1", "group1") // 参数一:触发器的名称;参数二:触发器组的名称,对触发器进行分组 
							.startNow()	// 启动时间,这里设置马上启动
							.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5))// 每5秒重复执行
							.build();
		// 最后,让调度器关联任务和触发器,保证按照触发器定义的条件去执行任务。
		scheduler.scheduleJob(jobDetail, trigger);
		// 启动
		scheduler.start();
	}
}

运行效果:

 

发布了128 篇原创文章 · 获赞 6 · 访问量 3230

Guess you like

Origin blog.csdn.net/weixin_43318134/article/details/103639167