Module: ECS::TimeManagement

Defined in:
lib/ecs/time_management.rb

Constant Summary collapse

@@period =

seconds

1.0
@@time_file =
''

Class Method Summary collapse

Class Method Details

.kill_time_fileObject



59
60
61
62
63
# File 'lib/ecs/time_management.rb', line 59

def self.kill_time_file
  raise "Cannot kill time file #{self.time_file}." unless self.prepare_time_file( self.time_file )
  File.unlink( self.time_file )
rescue
end

.next_available_timeslotObject



28
29
30
31
32
33
34
35
# File 'lib/ecs/time_management.rb', line 28

def self.next_available_timeslot
  if File.exist?( @@time_file )
    t = YAML.load_file( @@time_file )
    ( t.respond_to?( :to_f ) ? t : Time.now ).to_f
  else
    Time.now.to_f
  end
end

.next_available_timeslot=(float_timestamp = nil) ⇒ Object

Raises:

  • (ArgumentError)


37
38
39
40
41
# File 'lib/ecs/time_management.rb', line 37

def self.next_available_timeslot=( float_timestamp=nil )
  raise ArgumentError, "float_timestamp must be a floating point number" unless float_timestamp.respond_to?( :to_f )
  float_timestamp = Time.now.to_f if float_timestamp.nil?
  File.open( @@time_file, 'w' ) { |f| f << YAML.dump( float_timestamp.to_f ) }
end

.prepare_time_file(f) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/ecs/time_management.rb', line 47

def self.prepare_time_file( f )
  file = File.expand_path( f )
  FileUtils.touch( file ) unless File.exist?( file )
  File.writable?( file )
rescue
  false
end

.sleep_duration(schroedingers_cat = true) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/ecs/time_management.rb', line 11

def self.sleep_duration( schroedingers_cat=true )
  # if schroedingers_cat is true, observing the time_to_sleep affects
  # it, effectively adding @@period to it
  now = Time.now.to_f
  next_available = self.next_available_timeslot
  if schroedingers_cat == true
    if next_available > now - @@period
      next_available += @@period
    else
      next_available = now
    end
    self.next_available_timeslot = next_available
  end
  duration = next_available - now
  duration > 0 ? duration : 0
end

.time_fileObject



44
45
46
# File 'lib/ecs/time_management.rb', line 44

def self.time_file
  @@time_file
end

.time_file=(f = '') ⇒ Object



54
55
56
57
58
# File 'lib/ecs/time_management.rb', line 54

def self.time_file=( f='' )
  file = File.expand_path( f )
  raise "#{file} is an unacceptable time file." unless self.prepare_time_file( file )
  @@time_file = file
end