文档章节

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
CDH集群中YARN的参数配置

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

超人学院
2015/05/29
0
0
架构书籍推荐:Java中高级、架构师值得一读!

上周我们免费送出了6本关于Python的重量级技术书籍,推出后反响特别强烈,有一个和最后一名仅差了一个赞,不过我们还是额外加送了一本送给这位朋友,以资鼓励,从另一面也可以看出Java程序猿...

Java技术栈
04/14
0
0
多线程编程读书笔记之线程中断的本质

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

刘学炜
2012/07/03
0
0

没有更多内容

加载失败,请刷新页面

加载更多

活动推荐|互联网3.0与区块链新时代论坛(北京)

1 时间地点 **时间:**9月22日 14:00 - 18:00 地点:(北京海淀)西大街70号 3w咖啡 二层 2 活动详情 Harmony创始人Stephen及团队将介绍他们的区块链分片扩容技术。Stephen曾任Apple地图服务...

HiBlock
43分钟前
1
0
如何优雅的删除Redis的大key

关于Redis大键(Key),我们从[空间复杂性]和访问它的[时间复杂度]两个方面来定义大键。前者主要表示Redis键的占用内存大小;后者表示Redis集合数据类型(set/hash/list/sorted set)键,所含有的...

IT--小哥
53分钟前
1
0
spring cloud学习笔记

工具 eclipse 4.9 gradle 4.10.2 spring cloud Finchley.SR1 spring boot 2.0.4 build.gradle buildscript {ext {springBootVersion = '2.0.4.RELEASE'}repositories {jcenter()......

bobby2006
55分钟前
1
0
Tcl命令操作实验-----(5)

Vivado% proc myproc {arg} {puts $arg}Vivado% myproc mynamemynameVivado% if {2>1} {puts 2>1} else {puts 2<1}2>1...

whoisliang
今天
1
0
比特币钱包RPC的PHP调用方法

当我们希望在Php开发的网站中加入比特币支付功能时,需要解决的第一个 问题,就是如何在Php程序代码中调用比特币钱包的RPC API开发接口来实现 我们期望的功能,例如比特币的支付与接收。 例如...

汇智网教程
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部