文档章节

Java任务调度学习

请修改个人昵称
 请修改个人昵称
发布于 2017/02/14 14:55
字数 557
阅读 11
收藏 0

 1. Timer

package com.demo1.timer;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 当前线程创建两个新的子任务线程(Timer),第一个子任务延迟1s执行,第二个延迟5s执行
 * 10秒钟后关闭子任务线程(Timer),启用新线程返回“结束”
 * */
public class TimerTest extends TimerTask 
{
	private String jobNameStr = "";
	private static long currentTime = System.currentTimeMillis();
	
	public TimerTest(String jobName) 
	{
		super();
		this.jobNameStr = jobName;
	}
	
	@Override
	public void run() 
	{
		System.out.println("run "+jobNameStr);
	}
	
	public static void main(String[] args) throws InterruptedException, ExecutionException 
	{
		System.out.println("开始:"+currentTime);
		Timer timer = new Timer();
		
		long delay1 = 1*1000;
		long period1 = 1*1000;
		timer.schedule(new TimerTest("job1"), delay1, period1);
		
		long delay2 = 5*1000;
		long period2 = 1*1000;
		timer.schedule(new TimerTest("job2"), delay2, period2);
		
		Thread.sleep(10*1000);
		timer.cancel();
		
		CheckCurrentTime rt = new CheckCurrentTime();
		FutureTask<String> task = new FutureTask<String>(rt);
		new Thread(task, "CheckTime").start();
		String over = task.get();
		System.out.println(over);
	}
}

class CheckCurrentTime implements Callable<String>
{
	@Override
	public String call() throws Exception 
	{
		long currentTime = System.currentTimeMillis();
		String over = "结束:"+currentTime;
		return over;
	}
}

2. ScheduledExecutor

package com.demo1.scheduledexecutor;

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

public class ScheduledExecutorTest implements Runnable
{
	private String jobName = "";
	
	public ScheduledExecutorTest( String jobName ) 
	{
		super();
		this.jobName = jobName;
	}
	
	@Override
	public void run() 
	{
		System.out.println("execute "+jobName);
	}
	
	public static void main(String[] args) throws InterruptedException 
	{
		ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
		
		long initialDelay1 = 1;
		long period1 = 1;
		service.scheduleAtFixedRate(new ScheduledExecutorTest("job1"), initialDelay1, period1, TimeUnit.SECONDS);
		
		long initialDelay2 = 5;
		long period2 = 1;
		service.scheduleAtFixedRate(new ScheduledExecutorTest("job2"), initialDelay2, period2, TimeUnit.SECONDS);
		
		Thread.sleep(10*1000);
		service.shutdown();
	}
}

3. ScheduledExecutor + Calendar

package com.demo1.scheduledexecutor;

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

public class ScheduledExectorCalendarTest extends TimerTask
{
	private String jobName = "";
	
	public ScheduledExectorCalendarTest( String jobName ) 
	{
		super();
		this.jobName = jobName;
	}
	
	@Override
	public void run() 
	{
		System.out.println("execute "+jobName);
	}
	
	public Calendar getCurrentExecuteDate(Calendar currentDate,int executeDay,int executeHour,int executeMinute,int executeSecond)
	{
		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);
		
		boolean weekLater = false;
		if( executeDay<currentDayOfWeek )
		{
			weekLater = true;
		} else if( executeDay==currentDayOfWeek && executeHour<currentHour )
		{
			weekLater = true;
		} else if( executeDay==currentDayOfWeek && executeHour==currentHour && executeMinute<currentMinute )
		{
			weekLater = true;
		} else if( executeDay==currentDayOfWeek && executeHour==currentHour && executeMinute==currentMinute && executeSecond<currentSecond )
		{
			weekLater = true;
		}
		
		if( weekLater )
		{
			currentDate.set(Calendar.WEEK_OF_YEAR, currentWeekOfYear+1);
		}
		currentDate.set(Calendar.DAY_OF_WEEK, executeDay);
		currentDate.set(Calendar.HOUR_OF_DAY, executeHour);
		currentDate.set(Calendar.MINUTE, executeMinute);
		currentDate.set(Calendar.SECOND, executeSecond);
		
		return currentDate;
	}
	
	public static void main(String[] args) 
	{
		ScheduledExectorCalendarTest test = new ScheduledExectorCalendarTest("job1");
		
		Calendar currentDate = Calendar.getInstance();
		long currentTimeMillis = currentDate.getTime().getTime();
		
		Calendar executeDate = test.getCurrentExecuteDate(currentDate,3,16,1,0);
		long executeTimeMillis = executeDate.getTime().getTime();
		
		long delay = executeTimeMillis-currentTimeMillis;
		long period = 7 * 24 * 60 * 60 * 1000;
		ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
		service.scheduleAtFixedRate(test, delay, period, TimeUnit.MILLISECONDS);
	}
}

4. Quartz  ( quartz-1.8.6.jar , slf4j-api-1.7.21.jar )

package com.demo1.quartz;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;

public class QuartzTest implements Job
{
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException 
	{
		System.out.println("Generating report - "
				+ arg0.getJobDetail().getFullName() + ", type ="
				+ arg0.getJobDetail().getJobDataMap().get("type"));
		System.out.println(new Date().toString());
	}
	
	public static void main(String[] args) 
	{
		try 
		{
			//create Scheduler
			SchedulerFactory factory = new org.quartz.impl.StdSchedulerFactory();
			Scheduler scheduler = factory.getScheduler();
			scheduler.start();
			
			//create JobDetail
			JobDetail jobDetail = new JobDetail("myJob", "myJobGroup",QuartzTest.class);
			jobDetail.getJobDataMap().put("type", "FULL");
			
			//create Trigger
			Trigger trigger = TriggerUtils.makeWeeklyTrigger(3, 16, 30);
			trigger.setGroup("myTriggerGroup");
			trigger.setStartTime(TriggerUtils.getEvenSecondDate(new Date()));
			trigger.setName("myTrigger");
			
			scheduler.scheduleJob(jobDetail, trigger);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
}

 

本文转载自:http://www.ibm.com/developerworks/cn/java/j-lo-taskschedule/

共有 人打赏支持
请修改个人昵称
粉丝 6
博文 55
码字总数 7496
作品 0
合肥
程序员
私信 提问
阿里年薪50WJAVA工程师转大数据学习路线!

大数据有两个方向,一个是偏计算机的,另一个是偏经济的。你学过Java,所以你可以偏将计算机的。 Java程序员想转大数据可行吗?Java是全世界使用人数最多的编程语言。不少程序员选择Java做为...

JAVA丶学习
04/25
0
0
定时器 Quartz Java

1、几种任务调度的 Java 实现方法与比较 http://www.oschina.net/question/129540_28053 //特此感谢这篇文章的作者,我很喜欢这篇文章,里边介绍了好多关于目前定时器在工程中的使用,我总结...

soul_mate
2014/06/13
0
2
多线程编程读书笔记之线程中断的本质

Java试图提供过抢占式限制中断,但问题多多,例如已被废弃的Thread.stop、Thread.suspend和 Thread.resume等。另一方面,出于Java应用代码的健壮性的考虑,降低了编程门槛,减少不清楚底层机...

刘学炜
2012/07/03
0
0
CDH集群中YARN的参数配置

CDH集群中YARN的参数配置 前言:Hadoop 2.0之后,原先的MapReduce不在是简单的离线批处理MR任务的框架,升级为MapReduceV2(Yarn)版本,也就是把资源调度和任务分发两块分离开来。而在最新的...

超人学院
2015/05/29
0
0
JAVA多线程和并发基础面试问答

原文链接 译文连接 作者:Pankaj 译者:郑旭东 校对:方腾飞 多线程和并发问题是Java技术面试中面试官比较喜欢问的问题之一。在这里,从面试的角度列出了大部分重要的问题,但是你仍然应该牢...

雷神雨石
2014/07/19
0
2

没有更多内容

加载失败,请刷新页面

加载更多

thinkphp门窗定制电商平台-尺寸定制页面

这个门窗定制电商平台的目标是,消费者通过门窗定制平台,上传要定制门窗的尺寸数据下订单,电商平台分派订单给厂家商家定制商品,由厂家商家直接发货给消费者。消费者的资金托管在电商平台里...

乐兔CRM
8分钟前
0
0
全局光照---小结

中国龙-扬科
10分钟前
0
0
LAMP架构设置防盗链及访问控制

11月19日任务 11.25 配置防盗链 11.26 访问控制Directory 11.27 访问控制FilesMatch 配置防盗链 为什么要配置防盗链 第三方的站点可以通过引用的方式来获取本服务器上的资源如图片等,但是相...

robertt15
10分钟前
0
0
AWS 推出长期支持的 OpenJDK 免费分发版本 —— Amazon Corretto

简评:听说 Oracle JDK 要收费了,Oracle 要限制 Java 的商业或生产用途,针对这个问题,AWS 将会推出 Amazon Corretto。 Java 是 AWS 用户使用的最流行的编程语言之一,亚马逊一直致力于支持...

极光推送
16分钟前
0
0
Cloudinit如何判断虚拟机为初始化状态

Cloudinit简介 cloudinit是专为云环境中虚拟机的初始化而开发的工具,它从各种数据源读取相关数据并据此对虚拟机进行配置。常见的数据源包括:云平台的metadata服务、ConfigDrive等,常见的配...

空灵飞渡
27分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部