File: loop.rb

package info (click to toggle)
ruby-async 1.30.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 536 kB
  • sloc: ruby: 3,651; makefile: 4
file content (44 lines) | stat: -rw-r--r-- 621 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# frozen_string_literal: true

require 'async/reactor'

class Callback
	def initialize
		@reactor = Async::Reactor.new
	end
	
	def close
		@reactor.close
	end
	
	# If duration is 0, it will happen immediately after the task is started.
	def run(duration = 0)
		@reactor.run do |task|
			@reactor.after(duration) do
				@reactor.stop
			end
			
			yield(task) if block_given?
		end
	end
end


callback = Callback.new

begin
	callback.run do |task|
		while true
			task.sleep(2)
			puts "Hello from task!"
		end
	end
	
	while true
		callback.run(0)
		puts "Sleeping for 1 second"
		sleep(1)
	end
ensure
	callback.close
end