Java定时启动的3种方法

1、使用 Java类提供的定时启动功能,如下: 

		Date now = new Date();  // 从现在开始,指定时间内调用Task(任务
		new com.fronware.vaccess.util.TimetaskUtil(new Task(), now, 1000 * 60).start();
public class TimetaskUtil {
	TimerTask task;
	Date firstTime;
	long period;
	/**
	 * @param task
	 * @param firstTime
	 * @param period
	 */
	public TimetaskUtil(TimerTask task, Date firstTime, long period){
		this.task=task;
		this.firstTime=firstTime;
		this.period=period;
	}
	
	public void start(){
		Date now = new Date();
		Timer timer = new Timer();
		timer.schedule(task, firstTime, period);
	}
	
}

其中的Task是一个线程,这个线程如下:

class Task extends TimerTask {
		public void run() {
			System.out.println("定时启动执行");
		}
	}

2、可以用一个永真循环和线程休眠方法sleep(),如下:

public void run() {
		while(true){
			// 执行操作
			try {
				Thread.sleep(120000);//2min
			} catch (InterruptedException e) {
				Log4jUtil.error(e, e.fillInStackTrace());
			}
		}
	}

3、使用ScheduledExecutorService

ScheduledExecutorService接口 在ExecutorService的基础上,ScheduledExecutorService提供了按时间安排执行任务的功能,它提供的方法主要有:
  • schedule(task,initDelay):安排所提交的Callable或Runnable任务在initDelay指定的时间后执行。
  • scheduleAtFixedRate():安排所提交的Runnable任务按指定的间隔重复执行
  • scheduleWithFixedDelay():安排所提交的Runnable任务在每次执行完后,等待delay所指定的时间后重复执行。

package com.schedule.test01;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceTest {
	public static void main(String[] args) throws InterruptedException,ExecutionException {
		// 线程池
		ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
		// 定义任务
		Runnable task1 = new Runnable() {
			public void run() {
				System.out.println("Taskrepeating.");
			}
		};
		/*
		   command the task to execute
           initialDelay the time to delay first execution
           period the period between successive executions,exceptin will suppress
           unit the time unit of the initialDelay and period parameters
		 */
		final ScheduledFuture future1 = service.scheduleAtFixedRate(task1, 0,1, TimeUnit.SECONDS);
		// 取消定时任务
		ScheduledFuture future2 = service.schedule(new Callable() {
			public String call() {
				future1.cancel(true);
				return "taskcancelled!";
			}
		}, 10, TimeUnit.SECONDS);
		
		System.out.println(future2.get());
		// 关闭服务
		service.shutdown();
	}
}


 

 

 


 

你可能感兴趣的:(Java定时启动的3种方法)