java 定时任务

任务调度是指基于给定时间点,给定时间间隔或者给定执行次数自动执行任务

一 、简单的Timer实现

package com.chen.time;

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

public class MyTimerTask extends TimerTask {

	private String jobName = "";

	public MyTimerTask(String jobName) {
		super();
		this.jobName = jobName;

	}

	@Override
	public void run() {
		System.out.println("execute " + jobName);
	}

	public static void main(String[] args) {
		Timer timer = new Timer();
		long delay1 = 1 * 1000;
		long period1 = 1000;
		// 从现在开始 1 秒钟之后,每隔 1 秒钟执行一次 Task1
		timer.schedule(new MyTimerTask("Task1"), delay1, period1);
		long delay2 = 2 * 1000;
		long period2 = 2000;
		// 从现在开始 2 秒钟之后,每隔 2 秒钟执行一次 Task2
		timer.schedule(new MyTimerTask("Task2"), delay2, period2);
	}
}

output

execute Task1

execute Task1
execute Task2
execute Task1
execute Task1

execute Task2

Timer 的设计核心是一个 TaskList 和一个 TaskThread。Timer 将接收到的任务丢到自己的 TaskList 中,TaskList 按照 Task 的最初执行时间进行排序。TimerThread 在创建 Timer 时会启动成为一个守护线程。这个线程会轮询所有任务,找到一个最近要执行的任务,然后休眠,当到达最近要执行任务的开始时间点,TimerThread 被唤醒并执行该任务。之后 TimerThread 更新最近一个要执行的任务,继续休眠

二、ScheduledExecutorService 运行线程,执行定时任务

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MyRunTask implements Runnable {
	private String jobName = "";

	public MyRunTask(String jobName) {
		super();
		this.jobName = jobName;
	}

	@Override
	public void run() {
		System.out.println("run " + jobName);
	}

	public static void main(String[] args) {
		ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

		long initialDelay1 = 1;
		long period1 = 1;
		// 从现在开始1秒钟之后,每隔1秒钟执行一次job1
		service.scheduleAtFixedRate(new MyRunTask("job1"), initialDelay1, period1, TimeUnit.SECONDS);

		long initialDelay2 = 1;
		long delay2 = 1;
		// 从现在开始2秒钟之后,每隔2秒钟执行一次job2
		service.scheduleWithFixedDelay(new MyRunTask("job2"), initialDelay2, delay2, TimeUnit.SECONDS);
	}
}

ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为 :initialDelay, initialDelay+period, initialDelay+2*period, …;ScheduleWithFixedDelay 每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。由此可见,ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。

用 ScheduledExecutor 和 Calendar 实现复杂任务调度

Timer 和 ScheduledExecutor 都仅能提供基于开始时间与重复间隔的任务调度,不能胜任更加复杂的调度需求。比如,设置每星期二的 16:38:10 执行任务。该功能使用 Timer 和 ScheduledExecutor 都不能直接实现,但我们可以借助 Calendar 间接实现该功能。


public class ScheduledExceutorTest extends TimerTask {

	private String jobName = "";

	public ScheduledExceutorTest(String jobName) {
		super();
		this.jobName = jobName;
	}

	@Override
	public void run() {
		System.out.println("Date = " + new Date() + ", execute " + jobName);
	}

	/**
	 * 计算从当前时间currentDate开始,满足条件dayOfWeek, hourOfDay, minuteOfHour,
	 * secondOfMinite的最近时间
	 * 
	 * @return
	 */
	public Calendar getEarliestDate(Calendar currentDate, int dayOfWeek, int hourOfDay, int minuteOfHour,
			int secondOfMinite) {
		// 计算当前时间的WEEK_OF_YEAR,DAY_OF_WEEK, HOUR_OF_DAY, MINUTE,SECOND等各个字段值
		int currentWeekOfYear = currentDate.get(Calendar.WEEK_OF_YEAR);
		int currentDayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK);
		int currentHour = currentDate.get(Calendar.HOUR_OF_DAY);
		int currentMinute = currentDate.get(Calendar.MINUTE);
		int currentSecond = currentDate.get(Calendar.SECOND);

		// 如果输入条件中的dayOfWeek小于当前日期的dayOfWeek,则WEEK_OF_YEAR需要推迟一周
		boolean weekLater = false;
		if (dayOfWeek < currentDayOfWeek) {
			weekLater = true;
		} else if (dayOfWeek == currentDayOfWeek) {
			// 当输入条件与当前日期的dayOfWeek相等时,如果输入条件中的
			// hourOfDay小于当前日期的
			// currentHour,则WEEK_OF_YEAR需要推迟一周
			if (hourOfDay < currentHour) {
				weekLater = true;
			} else if (hourOfDay == currentHour) {
				// 当输入条件与当前日期的dayOfWeek, hourOfDay相等时,
				// 如果输入条件中的minuteOfHour小于当前日期的
				// currentMinute,则WEEK_OF_YEAR需要推迟一周
				if (minuteOfHour < currentMinute) {
					weekLater = true;
				} else if (minuteOfHour == currentSecond) {
					// 当输入条件与当前日期的dayOfWeek, hourOfDay,
					// minuteOfHour相等时,如果输入条件中的
					// secondOfMinite小于当前日期的currentSecond,
					// 则WEEK_OF_YEAR需要推迟一周
					if (secondOfMinite < currentSecond) {
						weekLater = true;
					}
				}
			}
		}
		if (weekLater) {
			// 设置当前日期中的WEEK_OF_YEAR为当前周推迟一周
			currentDate.set(Calendar.WEEK_OF_YEAR, currentWeekOfYear + 1);
		}
		// 设置当前日期中的DAY_OF_WEEK,HOUR_OF_DAY,MINUTE,SECOND为输入条件中的值。
		currentDate.set(Calendar.DAY_OF_WEEK, dayOfWeek);
		currentDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
		currentDate.set(Calendar.MINUTE, minuteOfHour);
		currentDate.set(Calendar.SECOND, secondOfMinite);
		return currentDate;

	}

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

		ScheduledExceutorTest test = new ScheduledExceutorTest("job1");
		// 获取当前时间
		Calendar currentDate = Calendar.getInstance();
		long currentDateLong = currentDate.getTime().getTime();
		System.out.println("Current Date = " + currentDate.getTime().toString());
		// 计算满足条件的最近一次执行时间
		Calendar earliestDate = test.getEarliestDate(currentDate, 3, 16, 38, 10);
		long earliestDateLong = earliestDate.getTime().getTime();
		System.out.println("Earliest Date = " + earliestDate.getTime().toString());
		// 计算从当前时间到最近一次执行时间的时间间隔
		long delay = earliestDateLong - currentDateLong;
		// 计算执行周期为一星期
		long period = 7 * 24 * 60 * 60 * 1000;
		ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
		// 从现在开始delay毫秒之后,每隔一星期执行一次job1
		service.scheduleAtFixedRate(test, delay, period, TimeUnit.MILLISECONDS);

	}
}
其他第三方 定时任务 :

Quartz http://www.quartz-scheduler.org/


JCronTab http://jcrontab.sourceforge.net/


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值