下面列出了java.util.TimerTask#cancel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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);
}
}
}
}
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);
}
/**
* 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);
}
}
}
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;
}
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;
}
}
}
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();
}
/**
* 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;
}
}
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);
}
/**
* 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;
}
/**
* 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;
}
}
}
private Closeable makeCloseable(Timer timer, final TimerTask timerTask) {
return new Closeable() {
@Override
public void close() throws IOException {
timerTask.cancel();
timer.purge();
}
};
}
@Override
public void deregister(Reloadable resource) {
LOG.debug("De-registering resource " + resource);
TimerTask timerTask = tasks.remove(resource);
if (timerTask != null) {
timerTask.cancel();
}
}
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);
}
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);
}
@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;
}
}
public boolean expire(YAbstractSession session) {
if (session != null) {
TimerTask task = _sessionMap.remove(session);
if (task != null) {
task.cancel();
TIMER.purge();
return true;
}
}
return false;
}
/**
* 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;
}
}
@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);
}
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);
}
/**
* 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;
}
}