Exemplo n.º 1
1
 /** Removes the task. */
 public void remove() {
   startTask.cancel();
   endTask.cancel();
   calendarService.removeFromTaskMap(id);
   calendarService.removeFromCurrentItems(this);
   calendarService.updateStateFromCurrentItems();
 }
Exemplo n.º 2
0
  void checkUserClockChange() {
    if (!hasUserClockTasks()) {
      return;
    }

    final long userClockSkew = Timer.userClockSkew();
    if (userClockSkew == 0) {
      return;
    }

    if (userClockSkew < 0) {
      for (int i = 1; i <= size; i++) {
        TimerTask task = queue[i];
        if (task != null && task.isUserClock) {
          task.nextExecutionTime -= userClockSkew;
          fixUp(i);
        }
      }
    } else {
      for (int i = size; i >= 1; i--) {
        TimerTask task = queue[i];
        if (task != null && task.isUserClock) {
          task.nextExecutionTime -= userClockSkew;
          fixDown(i);
        }
      }
    }
  }
Exemplo n.º 3
0
  private void resetClientTimer(Socket socket) {
    if (this.idleClientTimer == null) {
      if (log.logTrace()) {
        log.trace("No idle client timeout configured, skipping timer reset");
      }
      return;
    }

    if (log.logTrace()) {
      log.trace("Resetting idle client timer: " + System.identityHashCode(socket));
    }

    // Store this in a local so we don't have to worry about
    // the value changing underneath us.
    long timeout = this.idleClientTimeout;

    // Cancel the existing task for this socket ...
    TimerTask curTask = (TimerTask) this.socketActivity.get(socket);
    if (curTask != null) {
      curTask.cancel();
    }

    // And schedule a new one.
    TimerTask task = new IdleClientTimerTask(socket);
    this.socketActivity.put(socket, task);
    this.idleClientTimer.schedule(task, timeout);
  }
Exemplo n.º 4
0
  /*
   * Schedule a task.
   */
  private void scheduleImpl(TimerTask task, long delay, long period, boolean fixed) {
    synchronized (impl) {
      if (impl.cancelled) {
        throw new IllegalStateException("luni.41"); // $NON-NLS-1$
      }

      long when = delay + System.currentTimeMillis();

      if (when < 0) {
        throw new IllegalArgumentException("luni.42"); // $NON-NLS-1$
      }

      synchronized (task.lock) {
        if (task.isScheduled()) {
          throw new IllegalStateException("luni.43"); // $NON-NLS-1$
        }

        if (task.cancelled) {
          throw new IllegalStateException("luni.44"); // $NON-NLS-1$
        }

        task.when = when;
        task.period = period;
        task.fixedRate = fixed;
      }

      // insert the newTask into queue
      impl.insertTask(task);
    }
  }
Exemplo n.º 5
0
  /** The main timer loop. (See class comment.) */
  private void mainLoop() {
    while (true) {
      try {
        TimerTask task;
        boolean taskFired;
        synchronized (queue) {
          // Wait for queue to become non-empty
          // But no more than timeout value.
          while (queue.isEmpty() && queue.newTasksMayBeScheduled) {
            queue.wait(THREAD_TIMEOUT);
            if (queue.isEmpty()) {
              break;
            }
          }
          if (queue.isEmpty()) break; // Queue is empty and will forever remain; die

          // Handle a possible change of the user clock
          queue.checkUserClockChange();

          // Queue nonempty; look at first evt and do the right thing
          long currentTime, executionTime;
          task = queue.getMin();
          synchronized (task.lock) {
            if (task.state == TimerTask.CANCELLED) {
              queue.removeMin();
              continue; // No action required, poll queue again
            }
            currentTime = Timer.monotonicTimeMillis();
            executionTime = task.nextExecutionTime;

            if (taskFired = (executionTime <= currentTime)) {
              if (task.period == 0) { // Non-repeating, remove
                queue.removeMin();
                task.state = TimerTask.EXECUTED;
              } else { // Repeating task, reschedule
                queue.rescheduleMin(
                    task.period < 0 ? currentTime - task.period : executionTime + task.period);
              }
            }
          }
          if (!taskFired) { // Task hasn't yet fired; wait
            long timeout = executionTime - currentTime;
            if (queue.hasUserClockTasks() && timeout > Timer.USER_CLOCK_CHECK_PERIOD) {
              timeout = Timer.USER_CLOCK_CHECK_PERIOD;
            }
            queue.wait(timeout);
          }
        }
        if (taskFired) { // Task fired; run it, holding no locks
          try {
            task.run();
          } catch (Exception e) {
            // Cancel tasks that cause exceptions
            task.cancel();
          }
        }
      } catch (InterruptedException e) {
      }
    }
  }
Exemplo n.º 6
0
  protected void deregisterSocket(Socket socket) {
    TimerTask task = (TimerTask) this.socketActivity.remove(socket);
    if (task != null) {
      task.cancel();
    }

    super.deregisterSocket(socket);
  }
Exemplo n.º 7
0
  /**
   * Sets the nextExecutionTime associated with the head task to the specified value, and adjusts
   * priority queue accordingly.
   *
   * @param newTime new time to apply to head task execution.
   */
  void rescheduleMin(long newTime) {
    final TimerTask task = queue[1];

    task.nextExecutionTime = newTime;
    fixDown(1);

    if (task.isUserClock) {
      // Only the first execution is scheduled against the user clock.
      // Subsequent executions are scheduled based on delays.
      task.isUserClock = false;
      userClockTaskRemoved();
    }
  }
Exemplo n.º 8
0
 public synchronized boolean pause() {
   if (timer == null) {
     return false;
   }
   stateSync.lock();
   try {
     shouldRun = false;
     if (null != task) {
       task.cancel();
       task = null;
     }
     animThread = null;
     try {
       final long periodx2 = 2L * (long) (1000.0f / (float) fps);
       Thread.sleep(
           periodx2 > 20L
               ? periodx2
               : 20L); // max(2 x timer period, ~ 1/60), since we can't ctrl stopped threads
     } catch (InterruptedException e) {
     }
   } finally {
     stateSync.unlock();
   }
   return true;
 }
  /*
   *
   *   Date      By	Description
   * MM/DD/YYYY
   * ----------  --	-----------
   * 11/15/2002  INB	Created.
   *
   */
  public final void timerTask(TimerTask ttI) {
    try {
      if (ttI.getCode().equals(MetricsInterface.TT_METRICS)) {
        long now = System.currentTimeMillis();
        Rmap frame = ((MetricsInterface) getObject()).calculateMetrics(lastTime, now);
        if (frame != null) {
          getSource().addChild(frame);
        }
        lastTime = now;

      } else if (ttI.getCode().equals(LogStatusInterface.TT_LOG_STATUS)) {
        ((LogStatusInterface) getObject()).logStatus("Is running");
      }

    } catch (java.lang.Exception e) {
    }
  }
Exemplo n.º 10
0
  @Override
  public void onPause() {
    Log.d(TAG, "LoaderActivity paused");
    super.onPause();

    mTimerTask.cancel();
    mTimerTask = null;
  }
Exemplo n.º 11
0
 /** Schedules the start and end tasks of the calendar item. */
 public void scheduleTasks() {
   if (!executeNow) {
     timer.schedule(startTask, startDate);
   } else {
     startTask.run();
   }
   timer.schedule(endTask, endDate);
 }
  /**
   * Executes example.
   *
   * @param args Command line arguments, none required.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws Exception {
    Timer timer = new Timer("priceBars");

    // Start grid.
    final Grid g = GridGain.start("examples/config/example-streamer.xml");

    System.out.println();
    System.out.println(">>> Streaming price bars example started.");

    try {
      TimerTask task = scheduleQuery(g, timer);

      streamData(g);

      // Force one more run to get final results.
      task.run();

      timer.cancel();

      // Reset all streamers on all nodes to make sure that
      // consecutive executions start from scratch.
      g.compute()
          .broadcast(
              new Runnable() {
                @Override
                public void run() {
                  if (!ExamplesUtils.hasStreamer(g, "priceBars"))
                    System.err.println(
                        "Default streamer not found (is example-streamer.xml "
                            + "configuration used on all nodes?)");
                  else {
                    GridStreamer streamer = g.streamer("priceBars");

                    System.out.println("Clearing bars from streamer.");

                    streamer.reset();
                  }
                }
              })
          .get();
    } finally {
      GridGain.stop(true);
    }
  }
Exemplo n.º 13
0
 public void expire() {
   if (updateState(ST_INIT, ST_EXPIRED)) {
     try {
       task.run(this);
     } catch (Throwable t) {
       parent.logger.warning(
           "An exception was thrown by " + TimerTask.class.getSimpleName() + ".", t);
     }
   }
 }
Exemplo n.º 14
0
  /**
   * Schedule the specified timer task for execution at the specified time with the specified
   * period, in milliseconds. If period is positive, the task is scheduled for repeated execution;
   * if period is zero, the task is scheduled for one-time execution. Time is specified in
   * Date.getTime() format. This method checks timer state, task state, and initial execution time,
   * but not period.
   *
   * @param task task to be scheduled.
   * @param userTime the user time at which task is to be executed or <tt>null</tt> if the delay is
   *     specified
   * @param delay the delay in milliseconds before the task execution
   * @param period time in milliseconds between successive task executions.
   * @param isUserClock true if the time is bound to user clock
   * @throws IllegalArgumentException if <tt>time()</tt> is negative.
   * @throws IllegalStateException if task was already scheduled or cancelled, timer was cancelled,
   *     or timer thread terminated.
   */
  private void sched(TimerTask task, Date userTime, long delay, long period) {
    final boolean isUserClock = userTime != null;

    long time;

    if (isUserClock) {
      long t = userTime.getTime();
      if (t < 0) {
        throw new IllegalArgumentException("Illegal execution time.");
      }
      time = Timer.userTimeFromStart(t);
    } else {
      time = Timer.monotonicTimeFromStart(JVM.monotonicTimeMillis() + delay);
    }

    synchronized (queue) {
      if (!queue.newTasksMayBeScheduled) {
        throw new IllegalStateException("Timer already cancelled.");
      }

      /*
       * If the TimerThread has exited without an error
       * it is restarted. See the commentary in TimerThread.run.
       */
      if (thread == null || !thread.isAlive()) {
        thread = new TimerThread(queue);
        thread.start();
      }

      synchronized (task.lock) {
        if (task.state != TimerTask.VIRGIN) {
          throw new IllegalStateException("Task already scheduled or cancelled");
        }
        task.nextExecutionTime = time;
        task.period = period;
        task.state = TimerTask.SCHEDULED;
        task.isUserClock = isUserClock;
      }

      queue.add(task);
      if (queue.getMin() == task) queue.notify();
    }
  }
Exemplo n.º 15
0
    public void expire() {
      if (!state.compareAndSet(ST_INIT, ST_EXPIRED)) {
        return;
      }

      try {
        task.run(this);
      } catch (Throwable t) {
        if (logger.isWarnEnabled()) {
          logger.warn("An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t);
        }
      }
    }
Exemplo n.º 16
0
  public void messageReceived(int to, Message m) {

    DripMsg msg = (DripMsg) m;

    int newId = msg.get_metadata_id();
    int newSeqno = msg.get_metadata_seqno();

    log.debug("Received Msg: id=" + newId + ",seqno=" + newSeqno);

    if (newId != id) {
      log.debug("dropped, not ID " + id);
      return;
    }

    if ((newSeqno & ~DripConsts.DRIP_WAKEUP_BIT) == DripConsts.DRIP_SEQNO_NEWEST) {
      log.debug("dropped, a special seqno " + newSeqno);
      return;
    }

    switch (state) {
      case PROBING:
        seqno = newSeqno;
        log.info(
            "Receive: id=" + id + ",seqno=" + dripMsg.get_metadata_seqno() + " Heard Old Seqno");
        incrementSeqno();
        state = SENDING_SEQNO;
      case SENDING_SEQNO:
        if (seqno == newSeqno) {
          log.info(
              "Receive: id=" + id + ",seqno=" + dripMsg.get_metadata_seqno() + " Heard New Seqno");
          trickle.cancel();
          trickleTask.cancel();
          sendDone();
        }
      default:
    }
  }
Exemplo n.º 17
0
  public SimpleTimerTask setUp(final Runnable runnable, long delay) {
    synchronized (myTime2Task) {
      final long current = System.currentTimeMillis();
      final long targetTime = current + delay;

      final SimpleTimerTask result = new SimpleTimerTask(targetTime, runnable, this);

      ArrayList<SimpleTimerTask> tasks = myTime2Task.get(targetTime);
      if (tasks == null) {
        tasks = new ArrayList<SimpleTimerTask>(2);
        myTime2Task.put(targetTime, tasks);
      }
      tasks.add(result);

      if (targetTime < myNextScheduledTime) {
        if (myNextProcessingTask != null) {
          myNextProcessingTask.cancel();
        }
        scheduleNext(delay, targetTime);
      }

      return result;
    }
  }
Exemplo n.º 18
0
 /** Cancel any running Timer. */
 private void cancelTimer() {
   if (task != null) {
     task.cancel();
     task = null;
   }
 }
Exemplo n.º 19
0
    /** This method will be launched on separate thread for each Timer object. */
    @Override
    public void run() {
      while (true) {
        final TimerTask task;
        synchronized (this) {
          // need to check cancelled inside the synchronized block
          if (cancelled) {
            return;
          }
          if (tasks.isEmpty()) {
            if (finished) {
              return;
            }
            // no tasks scheduled -- sleep until any task appear
            try {
              this.wait();
            } catch (InterruptedException ignored) {
            }
            continue;
          }

          long currentTime = System.currentTimeMillis();

          task = tasks.minimum();
          long timeToSleep;

          synchronized (task.lock) {
            if (task.cancelled) {
              tasks.delete(0);
              continue;
            }

            // check the time to sleep for the first task scheduled
            timeToSleep = task.when - currentTime;
          }

          if (timeToSleep > 0) {
            // sleep!
            try {
              this.wait(timeToSleep);
            } catch (InterruptedException ignored) {
            }
            continue;
          }

          // no sleep is necessary before launching the task

          synchronized (task.lock) {
            int pos = 0;
            if (tasks.minimum().when != task.when) {
              pos = tasks.getTask(task);
            }
            if (task.cancelled) {
              tasks.delete(tasks.getTask(task));
              continue;
            }

            // set time to schedule
            task.setScheduledTime(task.when);

            // remove task from queue
            tasks.delete(pos);

            // set when the next task should be launched
            if (task.period >= 0) {
              // this is a repeating task,
              if (task.fixedRate) {
                // task is scheduled at fixed rate
                task.when = task.when + task.period;
              } else {
                // task is scheduled at fixed delay
                task.when = System.currentTimeMillis() + task.period;
              }

              // insert this task into queue
              insertTask(task);
            } else {
              task.when = 0;
            }
          }
        }

        boolean taskCompletedNormally = false;
        try {
          task.run();
          taskCompletedNormally = true;
        } finally {
          if (!taskCompletedNormally) {
            synchronized (this) {
              cancelled = true;
            }
          }
        }
      }
    }
Exemplo n.º 20
0
 /** Stops the cleaning thread. */
 public void finalize() {
   clean.cancel();
 }