Sha256: 5732bb2df4f6fa40535e5e0a1b76552aac0015c3178889de621ba89f32dfe7e4

Contents?: true

Size: 1.17 KB

Versions: 3

Compression:

Stored size: 1.17 KB

Contents

=begin

    This file is part of the Raktr project and may be subject to
    redistribution and commercial restrictions. Please see the Raktr
    web site for more information on licensing and terms of use.

=end

class Raktr
class Tasks

# @note {#interval Time} accuracy cannot be guaranteed.
#
# {Base Task} occurring every {#interval} seconds.
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@gmail.com>
class Periodic < Persistent

    # @return   [Float]
    attr_reader :interval

    # @param    [Float] interval
    #   Needs to be greater than `0.0`.
    # @param    [#call] task
    def initialize( interval, &task )
        interval = interval.to_f
        fail ArgumentError, 'Interval needs to be greater than 0.' if interval <= 0

        super( &task )

        @interval = interval
        calculate_next
    end

    # @return   [Object, nil]
    #   Return value of the configured task or `nil` if it's not
    #   {#interval time} yet.
    def call( *args )
        return if !call?
        calculate_next

        super( *args )
    end

    private

    def call?
        Time.now >= @next
    end

    def calculate_next
        @next = Time.now + @interval
    end

end

end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
raktr-0.0.3 lib/raktr/tasks/periodic.rb
raktr-0.0.2 lib/raktr/tasks/periodic.rb
raktr-0.0.1 lib/raktr/tasks/periodic.rb