Summarizes three ways to achieve the task scheduling and code examples - Multithreading: java learning

java task scheduling can be achieved in several ways summary

Scheduling means based on given point in time , a given time interval or a given frequency and perform automated tasks.

(1)Timmer

Use Timer realize task scheduling core classes are Timer and TimerTask. Timer which is responsible for setting the start time and intervals of TimerTask. Users only need to create a class to inherit TimerTask achieve their run method, and then threw Timer to perform to.

Timer advantage of being simple to use, but because all tasks are scheduling by the same thread, so all tasks are performed serially, at the same time only one task in execution, a task in front of delay or exception will after the task will be affected.

The following is a simple example Timmer class:

public class test {

	public static void main(String[] args) {
		final SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Timer timer = new Timer();
		// 从当前时间之后10秒开始执行,每2秒执行一次
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				String timeString=df.format(new Date());
				System.out.println("   "+timeString+  "  so easy......");
			}
		}, new Date(System.currentTimeMillis() + 10000), 2000);
	}
}

Results of the:
Here Insert Picture Description

(2)ScheduledExecutor

ScheduledExecutor is designed based on the thread pool.

The design philosophy is that each task will be scheduled to be executed by a thread pool thread, so the task is executed concurrently, without interference with each other. Note that, only when the execution time of the task arrival, ScheduedExecutor will really start a thread, the rest are ScheduledExecutor state polling task.

public class test {
	public static void main(String[] args) {
		ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
		/**
		 * 任务1
		 */
		long initialDelay1 = 6;
		long period1 = 2;
		// 从现在开始6秒钟之后,每隔2秒钟执行一次job1
		service.scheduleAtFixedRate(new MyRunnable("我的定时任务111啊"), initialDelay1,
				period1, TimeUnit.SECONDS);
		/**
		 * 任务2
		 */
		long initialDelay2 = 2;
		long period2 = 1;
		// 从现在开始6秒钟之后,每隔2秒钟执行一次job1
		service.scheduleAtFixedRate(new MyRunnable("我的定时任务222啊"), initialDelay2,
				period2, TimeUnit.SECONDS);	
	}
}
class MyRunnable implements Runnable {
	private String JobName;
	public MyRunnable() {
	}
	public MyRunnable(String JobName) {
		this.JobName = JobName;
	}
	@Override
	public void run() {
		System.out.println("正在执行----" + this.JobName);
	}
}

(3) open-source toolkit Quartz

Quartz core elements:
Scheduler: Task Scheduler, tasks are all from here.
Trigger: trigger, define the task execution interval.
JobDetail & Job: logical definition of specific tasks to perform.

Case: not a one minute to perform a total of two Job. The results shown in Figure:

Here Insert Picture Description

Main code:

public class MyCreateXml {
	public static void main(String args[]) throws Exception {

		run();
	}

	public static void run() throws Exception {
		System.out.println("------- 初始化Scheduler ---------");

		StdSchedulerFactory sf = new StdSchedulerFactory();
		// quartz的schedulerFactory实现解析。SchedulerFactory是一个接口,用于Scheduler的创建和管理。
		Properties props = new Properties();
		props.put("org.quartz.scheduler.instanceName", "MyScheduler");// 调度器属性
		props.put("org.quartz.threadPool.threadCount", "2");// 线程配置,线程池的数量

		sf.initialize(props);// 初始化
		Scheduler sched = sf.getScheduler();

		System.out.println("------- 初始化Scheduler完成 --------");

		System.out.println("------- Jobs配置 ----------------");

		JobDetail job1 = newJob(MyJob1.class).withIdentity("myJob-1",
				"my-job-1").build();
		JobDetail job2 = newJob(MyJob2.class).withIdentity("myJob-2",
				"my-job-2").build();

		CronTrigger trigger1 = newTrigger()
				.withIdentity("triggerForMe1", "my-trigger1")
				.withSchedule(cronSchedule("0 0/1 * * * ?")).build();// 这是一个触发器,每隔1分钟触发一次

		CronTrigger trigger2 = newTrigger()
				.withIdentity("triggerForMe2", "my-trigger2")
				.withSchedule(cronSchedule("0 0/1 * * * ?")).build();

		job1.getJobDataMap().put("MyName", "小兔子");
		job2.getJobDataMap().put("MyName", "小猪猪");

		Date scheduleTime1 = sched.scheduleJob(job1, trigger1);// 触发器trigger1,触发job1。
		Date scheduleTime2 = sched.scheduleJob(job2, trigger2);

		System.out.println(job1.getKey() + " has been scheduled to run at: "
				+ scheduleTime1 + " and repeat based on expression: "
				+ trigger1.getCronExpression());
		System.out.println(job2.getKey() + " has been scheduled to run at: "
				+ scheduleTime2 + " and repeat based on expression: "
				+ trigger2.getCronExpression());

		System.out.println("------- 开启任务调度器------");

		sched.start();

		System.out.println("------- 任务调度器已经开启 ------");

	}

}

Two Job:

public class MyJob1 implements Job{
	private String MyName;
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap data = context.getJobDetail().getJobDataMap();
		MyName = data.getString("MyName");
		System.err.println( MyName+" 啊,你长得真好看!!!");
		
	}
	public String getMyName() {
		return MyName;
	}
	public void setMyName(String myName) {
		MyName = myName;
	}
	

}

public class MyJob2 implements Job{
	private String MyName;
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap data = context.getJobDetail().getJobDataMap();
		MyName = data.getString("MyName");
		System.err.println( MyName+" 啊,你长得也好看!!!");
		
	}
	public String getMyName() {
		return MyName;
	}
	public void setMyName(String myName) {
		MyName = myName;
	}
	

}
Published 57 original articles · won praise 13 · views 1093

Guess you like

Origin blog.csdn.net/weixin_42924812/article/details/105256386