import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 设置开始时间开启任务,间隔时间执行任务,结束时间关闭任务
*
* @author
*
*/
public class ScheduldeExecutorTest {
//线程池能按时间计划来执行任务,允许用户设定计划执行任务的时间,int类型的参数是设定
//线程池中线程的最小数目。当任务较多时,线程池可能会自动创建更多的工作线程来执行任务
//此处用Executors.newSingleThreadScheduledExecutor()更佳。
public ScheduledExecutorService scheduExec = Executors.newScheduledThreadPool(1);
//启动计时器
public void lanuchTimer(){
Runnable task = new Runnable() {
public void run() {
throw new RuntimeException();
}
};
scheduExec.scheduleWithFixedDelay(task, 1000*5, 1000*10, TimeUnit.MILLISECONDS);
}
//添加新任务
public void addOneTask(){
Runnable task = new Runnable() {
public void run() {
//获取本系统时间,如果大于设定的时间就关闭服务
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String nowDate=df.format(new Date());
int c=timeCompare("2017-01-20 10:42:00", nowDate);
if(0>c){
System.out.println(nowDate+"时间到,关闭任务!");
scheduExec.shutdown();
}else{
System.out.println("==来了");
}
}
};
scheduExec.scheduleWithFixedDelay(task, 1000*1, 2000, TimeUnit.MILLISECONDS);
}
/*时间比大小*/
public static int timeCompare(String t1,String t2){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c1=Calendar.getInstance();
Calendar c2=Calendar.getInstance();
try {
c1.setTime(formatter.parse(t1));
c2.setTime(formatter.parse(t2));
} catch (Exception e) {
e.printStackTrace();
}
int result=c1.compareTo(c2);
return result;
}
public static void main(String[] args) throws Exception {
//开启
ScheduldeExecutorTest test = new ScheduldeExecutorTest();
test.lanuchTimer();
//Thread.sleep(1000*5);//5秒钟之后添加新任务
test.addOneTask();
}
}