定时任务(java)
来源:互联网 发布:2015家电市场销售数据 编辑:程序博客网 时间:2024/05/16 07:21
实现定时器的3种方法:
1.if,else
2.线程
3.calendar
第一种:先获取到当前时间
然后用当前的时间和设置的时间进行比较,if(){}else{}
第二种:线程
/**普通thread
*这是最常见的,创建一个thread,然后让它在while循环里一直运行着
*通过sleep方法来达到定时任务的效果,这样可以快速简单的现实
*/
public class Task{
public static void main (String[] args){
final long timeInterval=1000;
Runnable runnable= new Runnable(){
public void run(){
while (true){
-------执行语句-----
try{
Thread.sleep(timeInterval);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
};
Thread thread =new Thread(runnable);
thread.start();
}
}
第三种:// 安排指定的任务task在指定的时间firstTime开始进行重复的固定速率period执行.
// Timer.scheduleAtFixedRate(TimerTask task,Date firstTime,long period)
publicstaticvoidtimer4() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,12);// 控制时
calendar.set(Calendar.MINUTE,0);// 控制分
calendar.set(Calendar.SECOND,0);// 控制秒
Date time = calendar.getTime();// 得出执行任务的时间,此处为今天的12:00:00
Timer timer =new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
publicvoidrun() {
System.out.println("-------设定要指定任务--------");
} }, time,1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行 }}