Timer 及 TimerTask 相关使用代码

代码1:
package com.tg.email;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Timeer {

    
public static void showTimer() {
        TimerTask task 
= new TimerTask() {
            @Override
            
public void run() {
                System.out.print(
new SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis()));
                System.out.println(
"执行定时任务!!!");
            }
        };

        Calendar calendar 
= Calendar.getInstance();
        
int year = calendar.get(Calendar.YEAR);
        
int month = calendar.get(Calendar.MONTH);
        
int day = calendar.get(Calendar.DAY_OF_MONTH);
        
/*** 时间自己修改 ***/
        System.out.println(
"year:"+year);
        System.out.println(
"month:"+(month));
        System.out.println(
"day:"+day);
        
        calendar.set(year, month, day, 
130003);    //主要改这里,年、月、日、时、分、秒
        Date date = calendar.getTime();
        Timer timer 
= new Timer();
        timer.schedule(task, date,
1000);
    }


    
public static void main(String[] args) {
        showTimer();
    }
}
代码2:
package
 com.lzw.schedule;

import java.util.TimerTask;

public abstract class SchedulerTask implements Runnable
{
    
final Object lock = new Object();

    
int state = VIRGIN;

    
static final int VIRGIN = 0;

    
static final int SCHEDULED = 1;

    
static final int CANCELLED = 2;

    TimerTask timerTask 
= null;


    
protected SchedulerTask()
    {

    }


    
public abstract void run();


    
public boolean cancel()
    {
        
synchronized (lock)
        {
            
if (timerTask != null)
            {
                timerTask.cancel();
            }
            
boolean result = (state == SCHEDULED);

            state 
= CANCELLED;

            
return result;
        }
    }


    
public long scheduleExecutionTime()
    {
        
synchronized (lock)
        {
            
return timerTask == null ? 0 : timerTask.scheduledExecutionTime();
        }
    }
}
代码3:
package
 com.lzw.schedule;

public class AlarmClock
{
    
private final Scheduler scheduler = new Scheduler();

    
private final int hourofDay, minute, second;


    
public AlarmClock(int hourOfDay, int minute, int second)
    {
        
this.hourofDay = hourOfDay;
        
this.minute = minute;
        
this.second = second;
    }


    
public void start()
    {
        scheduler.schedule(
new SchedulerTask()
        {
            
public void run()
            {
                System.out.println(
"时间到");
            }
        }, 
new DailyIterator(hourofDay, minute, second));
    }


    
public static void main(String[] args)
    {
        AlarmClock alarmClock 
= new AlarmClock(17580);
        alarmClock.start();
    }
}
代码4:
package
 com.lzw.schedule;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Scheduler
{
    
class SchedulerTimerTask extends TimerTask
    {
        
private SchedulerTask schedulerTask = null;

        
private ScheduleIterator scheduleIterator = null;


        
public SchedulerTimerTask(SchedulerTask schedulerTask,
                                  ScheduleIterator scheduleIterator)
        {
            
this.schedulerTask = schedulerTask;
            
this.scheduleIterator = scheduleIterator;
        }


        
public void run()
        {
            schedulerTask.run();
            reschedule(schedulerTask, scheduleIterator);
        }
    }

    
private final Timer timer = new Timer();


    
public Scheduler()
    {
    }


    
public void cancel()
    {
        timer.cancel();
    }


    
public void schedule(SchedulerTask schedulerTask,
                         ScheduleIterator scheduleIterator)
    {
        Date time 
= scheduleIterator.next();

        
if (time == null)
        {
            schedulerTask.cancel();
        }
        
else
        {
            
synchronized (schedulerTask.lock)
            {
                
if (schedulerTask.state != SchedulerTask.VIRGIN)
                {
                    
throw new IllegalStateException("Task already scheduled or cancelled");
                }
                
                schedulerTask.state 
= SchedulerTask.SCHEDULED;

                schedulerTask.timerTask 
= new SchedulerTimerTask(schedulerTask,
                                                                 scheduleIterator);

                timer.schedule(schedulerTask.timerTask, time);
            }
        }
    }


    
private void reschedule(SchedulerTask schedulerTask,
                            ScheduleIterator scheduleIterator)
    {
        Date time 
= scheduleIterator.next();

        
if (time == null)
        {
            schedulerTask.cancel();
        }
        
else
        {
            
synchronized (schedulerTask.lock)
            {
                
if (schedulerTask.state != SchedulerTask.CANCELLED)
                {
                    schedulerTask.timerTask 
= new SchedulerTimerTask(schedulerTask,
                                                                     scheduleIterator);

                    timer.schedule(schedulerTask.timerTask, time);
                }
            }
        }
    }
}
代码5:
package
 com.lzw.schedule;

import java.util.Calendar;
import java.util.Date;

public interface ScheduleIterator
{
    
public Date next();
}


class DailyIterator implements ScheduleIterator
{

    
private final Calendar calendar = Calendar.getInstance();

    
public DailyIterator(int hourOfDay, int minute, int second, Date date)
    {
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, 
0);
        
        
if (!calendar.getTime().before(date)) {
            calendar.add(Calendar.DATE, 
-1);
        }
    }
    
    
public DailyIterator(int hourOfDay, int minute, int second)
    {
        Date date 
= new Date();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, 
0);
        
        
if (!calendar.getTime().before(date)) {
            calendar.add(Calendar.DATE, 
-1);
        }
    }
    
    
public Date next() {
        calendar.add(Calendar.DATE, 
1);
        
return calendar.getTime();
    }
}
代码6:
package
 com.lzw;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Test
{
    
private Calendar startSee = null//开始看病时间


    
public Test()
    {
        startSee 
= Calendar.getInstance();
        System.out.println(
"感冒了." + startSee.getTime().toLocaleString());
    }
    
    
public Date getScheduleDate(int day)
    {
//        startSee.add(Calendar.DATE, 1);   //按天来计算
        startSee.add(Calendar.SECOND, day); //按秒来计算
        return startSee.getTime();
    }

    
public void start(int day)
    {
       
final Timer timer = new Timer();
       
        timer.schedule(
new TimerTask()
        {
            
public void run()
            {
                System.out.println(
"回访啦.." + new Date().toLocaleString());
                
                timer.cancel();
            }
        }, getScheduleDate(day));
    }
    
    
public static void main(String[] args)
    {
        
//由于timer调系统时间不太起作用,所以拿秒来做测试.
        Test test = new Test();
        test.start(
10);  
        test.start(
15);  
        test.start(
20);  
        test.start(
30);  
    }
}
posted @ 2011-03-24 13:36  为牛马者,背负前行  阅读(516)  评论(0编辑  收藏  举报

如果本页面列出的内容侵犯了您的权益,请告知。
知识共享许可协议
996.icu