Last active
December 14, 2015 12:39
-
-
Save nelsnelson/5087823 to your computer and use it in GitHub Desktop.
This is a test of the future.cancel(true) method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env jruby | |
=begin | |
$ ./interrupt.rb | |
Current time: Monday March 4 03/04/2013 21:40:06.304 | |
Scheduled event for 10 seconds from now | |
f1: Current time: Monday March 4 03/04/2013 21:40:06.341 | |
Cancelling f1 | |
f2: Current time: Monday March 4 03/04/2013 21:40:11.357 | |
Got f1: Current time: Monday March 4 03/04/2013 21:40:11.361 | |
Got f2: Current time: Monday March 4 03/04/2013 21:40:11.362 | |
Sleeping to let other tasks finish before exiting | |
f0: Current time: Monday March 4 03/04/2013 21:40:16.294 | |
f1: Current time: Monday March 4 03/04/2013 21:40:16.342 | |
=end | |
import java.lang.InterruptedException | |
import java.lang.Runnable | |
import java.util.concurrent.Executors | |
import java.util.concurrent.TimeUnit | |
# Get the scheduler | |
@scheduler = Executors.newScheduledThreadPool(2) | |
@processor = Executors.newCachedThreadPool() | |
def delay_event(delay, &block) | |
future = @scheduler.schedule(block, delay.to_f * 1000, TimeUnit::MILLISECONDS) | |
end | |
def execute(&block) | |
future = @processor.java_send :submit, [ Runnable.java_class ], block | |
end | |
n = (ARGV.shift || 10).to_i | |
f0 = delay_event(n) { | |
puts "f0: Current time: " + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
} | |
puts "Current time: " + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
puts "Scheduled event for #{n} seconds from now" | |
f1 = execute { | |
begin | |
puts "f1: Current time: " + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
sleep 10 | |
puts "f1: Current time: " + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
rescue InterruptedException => ex | |
puts "Interrupted future f1" + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
end | |
} | |
f2 = delay_event(n/2) { | |
puts "Cancelling f1" | |
puts "f2: Current time: " + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
f1.cancel(true) | |
} | |
f1.get rescue nil | |
puts "Got f1: Current time: " + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
f2.get rescue nil | |
puts "Got f2: Current time: " + Time.now.strftime("%A %B %e %m/%d/%Y %H:%M:%S.%3N") | |
puts "Sleeping to let other tasks finish before exiting" | |
sleep n * 2 | |
puts "Done sleeping" | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment