java 定时执行任务

java 定时执行任务

固定某个时间,某个周期运行任务。

1. Timer定时器

封装与TimerTask类中。
用法,继承TimerTask类,创建Timer对象timer,schedule()调度。

2. Executor + 定时器调度

ScheduledExecutorService类
定时任务,周期任务。

例:
3个方法分别为:固定时间运行,固定速率,固定周期。
均为先创建executor对象,再调用schedule,scheduleAFixedRate,scheduleWithFixedDelay。进行调度。

package TimerTakk;

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

public class ScheduleExcutorTest {

	public static void main(String[] args) throws InterruptedException {
		//executorAtFixTime();
		//executorFixedRate();
		executorFixedDelay();
	}
	//固定时间点执行
	public static void executorAtFixTime() throws InterruptedException {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		executor.schedule(
				new task(), 
				1, 
				TimeUnit.SECONDS);
		
		Thread.sleep(20000);
		executor.shutdown();
	}
	
	//固定速率,上一个周期过去后,检测是否完成
	//若完成,立即执行,否则等待完成,再执行
	public static void executorFixedRate() throws InterruptedException {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		executor.scheduleAtFixedRate(
				new task(), 
				1, 
				3000, 
				TimeUnit.MILLISECONDS);
		Thread.sleep(20000);
		executor.shutdown();
	} 
	
	//周期任务,固定延时,从上一个任务结束开始计时
	public static void executorFixedDelay() throws InterruptedException {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		executor.scheduleWithFixedDelay(
				new task(), 
				1, 
				4, 
				TimeUnit.SECONDS);
		Thread.sleep(20000);
		executor.shutdown();
	}
}

class task implements Runnable{
	public void run() {
		System.out.println("task is running!" + new Date());
		try {
			Thread.sleep(1000);
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
	}
}

3. Quartz

第三方包,较为完善的任务调度框架。
解决Timer零星管理问题;
执行任务时,若出现异常,会继续执行(TImer不会)。
具体蛮复杂。

例:

package TimerTakk;

import org.quartz.JobDetail;
import org.quartz.Scheduler;

import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.JobBuilder.newJob;

public class QuartTest {

	public static void main(String[] args) throws Exception {
		//创建Scheduler
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		
		//创建Trigger
		Trigger trigger = (Trigger) newTrigger().withIdentity("trigger1", "group1")
				.startNow()
				.withSchedule(simpleSchedule()
				.withIntervalInSeconds(2)
				.repeatForever())
				.build();
		
		//定义一个JobDetail
		JobDetail job = newJob(HelloJob.class) 
				.withIdentity("job1", "group1")
				.usingJobData("name", "quartz")
				.build();
		
		//加入这个调度
		scheduler.scheduleJob(job, trigger);
		
		scheduler.start();
		
		Thread.sleep(10000);
		scheduler.shutdown();
	}
}
// HelloJob实现
package TimerTakk;

import java.util.Date;

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

public class HelloJob implements Job{

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDetail detail = context.getJobDetail();
		String name = detail.getJobDataMap().getString("name");
		System.out.println("hello from " + name + " at " + new Date());
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值