timer.java

来自「纯java操作系统jnode,安装简单和操作简单的个人使用的Java操作系统」· Java 代码 · 共 609 行 · 第 1/2 页

JAVA
609
字号
   * Timer has been finalized and no more tasks have to be executed.
   */
  private static final class Scheduler implements Runnable
  {
    // The priority queue containing all the TimerTasks.
    private TaskQueue queue;

    /**
     * Creates a new Scheduler that will schedule the tasks on the
     * given TaskQueue.
     */
    public Scheduler(TaskQueue queue)
    {
      this.queue = queue;
    }

    public void run()
    {
      TimerTask task;
      while ((task = queue.serve()) != null)
	{
	  // If this task has not been canceled
	  if (task.scheduled >= 0)
	    {

	      // Mark execution time
	      task.lastExecutionTime = task.scheduled;

	      // Repeatable task?
	      if (task.period < 0)
		{
		  // Last time this task is executed
		  task.scheduled = -1;
		}

	      // Run the task
	      try
		{
		  task.run();
		}
	      catch (Throwable t)
		{		
		  /* ignore all errors */
		}
	    }

	  // Calculate next time and possibly re-enqueue.
	  if (task.scheduled >= 0)
	    {
	      if (task.fixed)
		{
		  task.scheduled += task.period;
		}
	      else
		{
		  task.scheduled = task.period + System.currentTimeMillis();
		}

	      try
	        {
	          queue.enqueue(task);
		}
	      catch (IllegalStateException ise)
	        {
		  // Ignore. Apparently the Timer queue has been stopped.
		}
	    }
	}
    }
  }				// Scheduler

  // Number of Timers created.
  // Used for creating nice Thread names.
  private static int nr = 0;

  // The queue that all the tasks are put in.
  // Given to the scheduler
  private TaskQueue queue;

  // The Scheduler that does all the real work
  private Scheduler scheduler;

  // Used to run the scheduler.
  // Also used to checked if the Thread is still running by calling
  // thread.isAlive(). Sometimes a Thread is suddenly killed by the system
  // (if it belonged to an Applet).
  private Thread thread;

  // When cancelled we don't accept any more TimerTasks.
  private boolean canceled;

  /**
   * Creates a new Timer with a non daemon Thread as Scheduler, with normal
   * priority and a default name.
   */
  public Timer()
  {
    this(false);
  }

  /**
   * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
   * with normal priority and a default name.
   */
  public Timer(boolean daemon)
  {
    this(daemon, Thread.NORM_PRIORITY);
  }

  /**
   * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
   * with the priority given and a default name.
   */
  private Timer(boolean daemon, int priority)
  {
    this(daemon, priority, "Timer-" + (++nr));
  }

  /**
   * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
   * with the priority and name given.E
   */
  private Timer(boolean daemon, int priority, String name)
  {
    canceled = false;
    queue = new TaskQueue();
    scheduler = new Scheduler(queue);
    thread = new Thread(scheduler, name);
    thread.setDaemon(daemon);
    thread.setPriority(priority);
    thread.start();
  }

  /**
   * Cancels the execution of the scheduler. If a task is executing it will
   * normally finish execution, but no other tasks will be executed and no
   * more tasks can be scheduled.
   */
  public void cancel()
  {
    canceled = true;
    queue.stop();
  }

  /**
   * Schedules the task at Time time, repeating every period
   * milliseconds if period is positive and at a fixed rate if fixed is true.
   *
   * @exception IllegalArgumentException if time is negative
   * @exception IllegalStateException if the task was already scheduled or
   * canceled or this Timer is canceled or the scheduler thread has died
   */
  private void schedule(TimerTask task, long time, long period, boolean fixed)
  {
    if (time < 0)
      throw new IllegalArgumentException("negative time");

    if (task.scheduled == 0 && task.lastExecutionTime == -1)
      {
	task.scheduled = time;
	task.period = period;
	task.fixed = fixed;
      }
    else
      {
	throw new IllegalStateException
	  ("task was already scheduled or canceled");
      }

    if (!this.canceled && this.thread != null)
      {
	queue.enqueue(task);
      }
    else
      {
	throw new IllegalStateException
	  ("timer was canceled or scheduler thread has died");
      }
  }

  private static void positiveDelay(long delay)
  {
    if (delay < 0)
      {
	throw new IllegalArgumentException("delay is negative");
      }
  }

  private static void positivePeriod(long period)
  {
    if (period < 0)
      {
	throw new IllegalArgumentException("period is negative");
      }
  }

  /**
   * Schedules the task at the specified data for one time execution.
   *
   * @exception IllegalArgumentException if date.getTime() is negative
   * @exception IllegalStateException if the task was already scheduled or
   * canceled or this Timer is canceled or the scheduler thread has died
   */
  public void schedule(TimerTask task, Date date)
  {
    long time = date.getTime();
    schedule(task, time, -1, false);
  }

  /**
   * Schedules the task at the specified date and reschedules the task every
   * period milliseconds after the last execution of the task finishes until
   * this timer or the task is canceled.
   *
   * @exception IllegalArgumentException if period or date.getTime() is
   * negative
   * @exception IllegalStateException if the task was already scheduled or
   * canceled or this Timer is canceled or the scheduler thread has died
   */
  public void schedule(TimerTask task, Date date, long period)
  {
    positivePeriod(period);
    long time = date.getTime();
    schedule(task, time, period, false);
  }

  /**
   * Schedules the task after the specified delay milliseconds for one time
   * execution.
   *
   * @exception IllegalArgumentException if delay or
   * System.currentTimeMillis + delay is negative
   * @exception IllegalStateException if the task was already scheduled or
   * canceled or this Timer is canceled or the scheduler thread has died
   */
  public void schedule(TimerTask task, long delay)
  {
    positiveDelay(delay);
    long time = System.currentTimeMillis() + delay;
    schedule(task, time, -1, false);
  }

  /**
   * Schedules the task after the delay milliseconds and reschedules the
   * task every period milliseconds after the last execution of the task
   * finishes until this timer or the task is canceled.
   *
   * @exception IllegalArgumentException if delay or period is negative
   * @exception IllegalStateException if the task was already scheduled or
   * canceled or this Timer is canceled or the scheduler thread has died
   */
  public void schedule(TimerTask task, long delay, long period)
  {
    positiveDelay(delay);
    positivePeriod(period);
    long time = System.currentTimeMillis() + delay;
    schedule(task, time, period, false);
  }

  /**
   * Schedules the task at the specified date and reschedules the task at a
   * fixed rate every period milliseconds until this timer or the task is
   * canceled.
   *
   * @exception IllegalArgumentException if period or date.getTime() is
   * negative
   * @exception IllegalStateException if the task was already scheduled or
   * canceled or this Timer is canceled or the scheduler thread has died
   */
  public void scheduleAtFixedRate(TimerTask task, Date date, long period)
  {
    positivePeriod(period);
    long time = date.getTime();
    schedule(task, time, period, true);
  }

  /**
   * Schedules the task after the delay milliseconds and reschedules the task
   * at a fixed rate every period milliseconds until this timer or the task
   * is canceled.
   *
   * @exception IllegalArgumentException if delay or
   * System.currentTimeMillis + delay is negative
   * @exception IllegalStateException if the task was already scheduled or
   * canceled or this Timer is canceled or the scheduler thread has died
   */
  public void scheduleAtFixedRate(TimerTask task, long delay, long period)
  {
    positiveDelay(delay);
    positivePeriod(period);
    long time = System.currentTimeMillis() + delay;
    schedule(task, time, period, true);
  }

  /**
   * Tells the scheduler that the Timer task died
   * so there will be no more new tasks scheduled.
   */
  protected void finalize()
  {
    queue.setNullOnEmpty(true);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?