Java Code Examples for java.util.TimerTask#cancel()

The following examples show how to use java.util.TimerTask#cancel() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: incubator-tuweni   File: State.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Acts on receiving the full message.
 * 
 * @param sender the sender - may be null if we are submitting this message to the network
 * @param message the payload to send to the network
 */
void fullMessageReceived(@Nullable Peer sender, String attributes, Bytes message) {
  if (receivedFullMessage.compareAndSet(false, true)) {
    for (TimerTask task : tasks) {
      task.cancel();
    }

    if (sender == null || messageValidator.validate(message, sender)) {
      for (Peer peer : peerRepository.eagerPushPeers()) {
        if (sender == null || !sender.equals(peer)) {
          messageSender.sendMessage(MessageSender.Verb.GOSSIP, attributes, peer, hash, message);
        }
      }
      lazyQueue
          .addAll(
              peerRepository
                  .lazyPushPeers()
                  .stream()
                  .filter(p -> !lazyPeers.contains(p))
                  .map(
                      peer -> (Runnable) (() -> messageSender
                          .sendMessage(MessageSender.Verb.IHAVE, null, peer, hash, null)))
                  .collect(Collectors.toList()));
      if (sender != null) {
        messageListener.listen(message, attributes);
      }
    }
  } else {
    if (sender != null) {
      if (peerPruningFunction.prunePeer(sender)) {
        messageSender.sendMessage(MessageSender.Verb.PRUNE, null, sender, hash, null);
      }
    }
  }
}
 
Example 2
public void schedule(String taskIdentifier, TimerTask task) {
    TimerTask existingTask = taskMap.get(taskIdentifier);

    taskMap.put(taskIdentifier, task);
    if (existingTask != null) {
        existingTask.cancel();
        timer.purge(); // Clear existing cancelled requests.
    }

    timer.schedule(task, debounceDelayMilliSeconds);
}
 
Example 3
Source Project: cava   File: State.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Acts on receiving the full message
 * 
 * @param sender the sender - may be null if we are submitting this message to the network
 * @param message the payload to send to the network
 */
void fullMessageReceived(@Nullable Peer sender, Bytes message) {
  if (receivedFullMessage.compareAndSet(false, true)) {
    for (TimerTask task : tasks) {
      task.cancel();
    }

    if (sender == null || messageValidator.validate(message, sender)) {
      for (Peer peer : peerRepository.eagerPushPeers()) {
        if (sender == null || !sender.equals(peer)) {
          messageSender.sendMessage(MessageSender.Verb.GOSSIP, peer, hash, message);
        }
      }
      lazyQueue.addAll(
          peerRepository
              .lazyPushPeers()
              .stream()
              .filter(p -> !lazyPeers.contains(p))
              .map(peer -> (Runnable) (() -> messageSender.sendMessage(MessageSender.Verb.IHAVE, peer, hash, null)))
              .collect(Collectors.toList()));
      messageListener.accept(message);
    }
  } else {
    if (sender != null) {
      messageSender.sendMessage(MessageSender.Verb.PRUNE, sender, hash, null);
      peerRepository.moveToLazy(sender);
    }
  }
}
 
Example 4
AckClosure removeAck(String guid) {
    AckClosure ackClosure;
    BlockingQueue<PubAck> pac;
    TimerTask timerTask = null;
    this.lock();
    try {
        ackClosure = pubAckMap.get(guid);
        if (ackClosure != null) {
            timerTask = ackClosure.ackTask;
            pubAckMap.remove(guid);
        }
        pac = pubAckChan;
    } finally {
        this.unlock();
    }

    // Cancel timer if needed
    if (timerTask != null) {
        timerTask.cancel();
    }

    // Remove from channel to unblock async publish
    if (ackClosure != null && pac.size() > 0) {
        try {
            // remove from queue to unblock publish
            pac.take();
        } catch (InterruptedException e) {
            // TODO:  Ignore, but re-evaluate this
        }
    }

    return ackClosure;
}
 
Example 5
Source Project: apollo-android   File: RealSubscriptionManager.java    License: MIT License 5 votes vote down vote up
void cancelTask(int taskId) {
  synchronized (this) {
    TimerTask timerTask = tasks.remove(taskId);
    if (timerTask != null) {
      timerTask.cancel();
    }

    if (tasks.isEmpty() && timer != null) {
      timer.cancel();
      timer = null;
    }
  }
}
 
Example 6
protected void importGeometry(ODatabaseDocumentTx db, String file, final String clazz, String geomClazz) throws IOException {

    OClass points = db.getMetadata().getSchema().createClass(clazz);
    points.createProperty("geometry", OType.EMBEDDED, db.getMetadata().getSchema().getClass(geomClazz));
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    OIOUtils.copyStream(new FileInputStream(new File(file)), out, -1);
    ODocument doc = new ODocument().fromJSON(out.toString(), "noMap");
    List<ODocument> collection = doc.field("collection");

//    OShapeFactory builder = OShapeFactory.INSTANCE;

    final AtomicLong atomicLong = new AtomicLong(0);

    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        OLogManager.instance().info(this, clazz + " per second [%d]", atomicLong.get());
        atomicLong.set(0);
      }
    };
    Orient.instance().scheduleTask(task, 1000, 1000);
    for (ODocument entries : collection) {
      ODocumentInternal.removeOwner(entries, doc);
      ODocumentInternal.removeOwner(entries, (ORecordElement) collection);
      entries.setClassName(clazz);
      String wkt = entries.field("GeometryWkt");
      try {
//        ODocument location = builder.toDoc(wkt);
//        entries.field("geometry", location, OType.EMBEDDED);
//        db.save(entries);
//
//        atomicLong.incrementAndGet();
      } catch (Exception e) {

      }
    }
    task.cancel();
  }
 
Example 7
Source Project: navi-pbrpc   File: TimeoutEvictionTimer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Remove the specified eviction task from the timer.
 * 
 * @param task
 *            Task to be scheduled
 */
public static synchronized void cancel(TimerTask task) {
    if (task == null) {
        return;
    }
    task.cancel();
    usageCount.decrementAndGet();
    if (usageCount.get() == 0) {
        timer.cancel();
        timer = null;
    }
}
 
Example 8
Source Project: tddl   File: BufferedLogWriter.java    License: Apache License 2.0 5 votes vote down vote up
private final synchronized void schdeuleFlush() {
    TimerTask cancelTask = this.flushTask;
    this.flushTask = new TimerTask() {

        public void run() {
            // XXX: 定时器的执行应当耗时非常短
            flush(true);
        }
    };
    if (cancelTask != null) {
        cancelTask.cancel();
    }
    final long flushPriod = flushInterval * 1000;
    flushTimer.scheduleAtFixedRate(flushTask, flushPriod, flushPriod);
}
 
Example 9
/**
 * Cancels the execution of state machines for the given cycle period. This
 * stops the execution of state machines which are registered for the given
 * cycle period and cancels the executing {@link TimerTask}.
 *
 * @return {@code true} if poperly cancelled
 */
public boolean cancelAll(long cyclePeriod) {
	if (timer != null && timerTasks.containsKey(cyclePeriod)) {
		TimerTask task = timerTasks.get(cyclePeriod);
		task.cancel();
		timer.purge();
		timerTasks.remove(cyclePeriod);
		return true;
	}
	return false;
}
 
Example 10
/**
 * Stop tracking of runtime it is was registered before, otherwise do nothing.
 *
 * @param runtimeId identifier of runtime that should not be tracked anymore
 */
public synchronized void stopTracking(RuntimeIdentity runtimeId) {
  TimerTask timerTask = workspaceId2Task.remove(runtimeId.getWorkspaceId());
  if (timerTask != null) {
    LOG.debug("Tracking task for workspace {} is canceled", runtimeId.getWorkspaceId());
    timerTask.cancel();

    if (workspaceId2Task.isEmpty()) {
      timeouts.cancel();
      timeouts = null;
    }
  }
}
 
Example 11
private Closeable makeCloseable(Timer timer, final TimerTask timerTask) {
  return new Closeable() {
    @Override
    public void close() throws IOException {
      timerTask.cancel();
      timer.purge();
    }
  };
}
 
Example 12
Source Project: cfg4j   File: PeriodicalReloadStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deregister(Reloadable resource) {
  LOG.debug("De-registering resource " + resource);

  TimerTask timerTask = tasks.remove(resource);
  if (timerTask != null) {
    timerTask.cancel();
  }
}
 
Example 13
Source Project: tddl5   File: BufferedLogWriter.java    License: Apache License 2.0 5 votes vote down vote up
private final synchronized void schdeuleFlush() {
    TimerTask cancelTask = this.flushTask;
    this.flushTask = new TimerTask() {

        public void run() {
            // XXX: 定时器的执行应当耗时非常短
            flush(true);
        }
    };
    if (cancelTask != null) {
        cancelTask.cancel();
    }
    final long flushPriod = flushInterval * 1000;
    flushTimer.scheduleAtFixedRate(flushTask, flushPriod, flushPriod);
}
 
Example 14
Source Project: tddl5   File: SoftRefLogWriter.java    License: Apache License 2.0 5 votes vote down vote up
private final synchronized void schdeuleFlush() {
    TimerTask cancelTask = this.flushTask;
    this.flushTask = new TimerTask() {

        public void run() {
            // XXX: 定时器的执行应当耗时非常短
            flush();
        }
    };
    if (cancelTask != null) {
        cancelTask.cancel();
    }
    final long flushPriod = flushInterval * 1000;
    flushTimer.scheduleAtFixedRate(flushTask, flushPriod, flushPriod);
}
 
Example 15
Source Project: commons-pool   File: TestPoolUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckMinIdleKeyedObjectPoolKeys() throws Exception {
    // Because this isn't deterministic and you can get false failures, try more than once.
    AssertionFailedError afe = null;
    int triesLeft = 3;
    do {
        afe = null;
        final List<String> calledMethods = new ArrayList<>();
        try (@SuppressWarnings("unchecked")
        final KeyedObjectPool<String, Object> pool = createProxy(KeyedObjectPool.class, calledMethods)) {
            final Collection<String> keys = new ArrayList<>(2);
            keys.add("one");
            keys.add("two");
            // checks minIdle immediately
            final Map<String, TimerTask> tasks = PoolUtils.checkMinIdle(pool, keys, 1, CHECK_PERIOD);

            Thread.sleep(CHECK_SLEEP_PERIOD); // will check CHECK_COUNT more times.
            for (final TimerTask task : tasks.values()) {
                task.cancel();
            }

            final List<String> expectedMethods = new ArrayList<>();
            for (int i = 0; i < CHECK_COUNT * keys.size(); i++) {
                expectedMethods.add("getNumIdle");
                expectedMethods.add("addObject");
            }
            assertEquals(expectedMethods, calledMethods); // may fail because of the thread scheduler
        } catch (final AssertionFailedError e) {
            afe = e;
        }
    } while (--triesLeft > 0 && afe != null);
    if (afe != null) {
        throw afe;
    }
}
 
Example 16
public boolean expire(YAbstractSession session) {
    if (session != null) {
        TimerTask task = _sessionMap.remove(session);
        if (task != null) {
            task.cancel();
            TIMER.purge();
            return true;
        }
    }
    return false;
}
 
Example 17
/**
 * Remove the specified eviction task from the timer.
 *
 * @param task Task to be scheduled
 */
public static synchronized void cancel(TimerTask task) {
    if (task == null) {
        return;
    }
    task.cancel();
    usageCount.decrementAndGet();
    if (usageCount.get() == 0) {
        timer.cancel();
        timer = null;
    }
}
 
Example 18
Source Project: ClockView   File: DownloadActivity.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download);
    down = (TextView) findViewById(R.id.down);
    progress = (TextView) findViewById(R.id.progress);
    file_name = (TextView) findViewById(R.id.file_name);
    pb_update = (ProgressBar) findViewById(R.id.pb_update);
    down.setOnClickListener(this);
    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    request = new DownloadManager.Request(Uri.parse(downloadUrl));

    request.setTitle("测试apk包");
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    request.setAllowedOverRoaming(false);
    request.setMimeType("application/vnd.android.package-archive");
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //创建目录
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ;

    //设置文件存放路径
    request.setDestinationInExternalPublicDir(  Environment.DIRECTORY_DOWNLOADS  , "app-release.apk" ) ;
    pb_update.setMax(100);
   final  DownloadManager.Query query = new DownloadManager.Query();
    timer = new Timer();
    task = new TimerTask() {
        @Override
        public void run() {
            Cursor cursor = downloadManager.query(query.setFilterById(id));
            if (cursor != null && cursor.moveToFirst()) {
                if (cursor.getInt(
                        cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                    pb_update.setProgress(100);
                    install(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/app-release.apk" );
                    task.cancel();
                }
                String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                String address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                int pro =  (bytes_downloaded * 100) / bytes_total;
                Message msg =Message.obtain();
                Bundle bundle = new Bundle();
                bundle.putInt("pro",pro);
                bundle.putString("name",title);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
            cursor.close();
        }
    };
    timer.schedule(task, 0,1000*3);
}
 
Example 19
protected void startPrintService() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int savemode = 4000;
    if (prefs.getBoolean("battery", false)){
        savemode = 20000;
    }
    final boolean notef = prefs.getBoolean("stick", true);
    final int id = 1;
    Log.d("OctoDroid Service", "StartprintService");


        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("OctoDroid")
                .setContentText("Printing")
                .setOngoing(true)
                .setSmallIcon(R.drawable.octodroid_smal);
    if (notef && !notefaRunning) {
        mNotifyManager.notify(id, mBuilder.build());
        notefaRunning = true;
    }

    timerTask2 = new TimerTask() {
        @Override
        public void run() {
            Log.d("OctoDroid Service", "startPrintService timertask");
            try {
                util_decode.decodeConnections();
                util_decode.decodeJob();
                complete = memory.job.progress.completion;
            }catch (Exception e){
                complete = 0;
            }
            if (!memory.connection.current.getState().equals("Printing")) {
                Log.d("OctoDroid Service", "startPrintService stopping");
                mainActivity.printing = false;
                notefaRunning = false;
                mNotifyManager.cancel(id);
                Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                mBuilder.setContentText("Print complete")
                        .setContentTitle("OctoDroid")
                        .setSound(soundUri)
                        .setSmallIcon(R.drawable.octodroid_smal)
                        .setOngoing(false)
                        .setProgress(0, 0, false);
                mNotifyManager.notify(id, mBuilder.build());
                timerTask2.cancel();
                runner();
                return;
            }
            Log.d("OctoDroid Service", "startPrintService Notify" + complete );
            if (notef) {
                mBuilder.setProgress(100, (int) complete, false).setContentText("Printing (" + (int) complete + "%)");
                mNotifyManager.notify(id, mBuilder.build());
            }
        }
    };
    timer2.schedule(timerTask2, 0, savemode);
}
 
Example 20
Source Project: Kademlia   File: KadServer.java    License: MIT License 4 votes vote down vote up
/**
 * Listen for incoming messages in a separate thread
 */
private void listen()
{
    try
    {
        while (isRunning)
        {
            try
            {
                /* Wait for a packet */
                byte[] buffer = new byte[DATAGRAM_BUFFER_SIZE];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);

                /* Lets inform the statistician that we've received some data */
                this.statistician.receivedData(packet.getLength());

                if (this.config.isTesting())
                {
                    /**
                     * Simulating network latency
                     * We pause for 1 millisecond/100 bytes
                     */
                    int pause = packet.getLength() / 100;
                    try
                    {
                        Thread.sleep(pause);
                    }
                    catch (InterruptedException ex)
                    {

                    }
                }

                /* We've received a packet, now handle it */
                try (ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength());
                        DataInputStream din = new DataInputStream(bin);)
                {

                    /* Read in the conversation Id to know which handler to handle this response */
                    int comm = din.readInt();
                    byte messCode = din.readByte();

                    Message msg = messageFactory.createMessage(messCode, din);
                    din.close();

                    /* Get a receiver for this message */
                    Receiver receiver;
                    if (this.receivers.containsKey(comm))
                    {
                        /* If there is a reciever in the receivers to handle this */
                        synchronized (this)
                        {
                            receiver = this.receivers.remove(comm);
                            TimerTask task = (TimerTask) tasks.remove(comm);
                            if (task != null)
                            {
                                task.cancel();
                            }
                        }
                    }
                    else
                    {
                        /* There is currently no receivers, try to get one */
                        receiver = messageFactory.createReceiver(messCode, this);
                    }

                    /* Invoke the receiver */
                    if (receiver != null)
                    {
                        receiver.receive(msg, comm);
                    }
                }
            }
            catch (IOException e)
            {
                //this.isRunning = false;
                System.err.println("Server ran into a problem in listener method. Message: " + e.getMessage());
            }
        }
    }
    finally
    {
        if (!socket.isClosed())
        {
            socket.close();
        }
        this.isRunning = false;
    }
}