timers.scm 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. ;;; Hoot implementation of Fibers
  2. ;;; Copyright (C) 2024 Igalia, S.L.
  3. ;;;
  4. ;;; Licensed under the Apache License, Version 2.0 (the "License");
  5. ;;; you may not use this file except in compliance with the License.
  6. ;;; You may obtain a copy of the License at
  7. ;;;
  8. ;;; http://www.apache.org/licenses/LICENSE-2.0
  9. ;;;
  10. ;;; Unless required by applicable law or agreed to in writing, software
  11. ;;; distributed under the License is distributed on an "AS IS" BASIS,
  12. ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. ;;; See the License for the specific language governing permissions and
  14. ;;; limitations under the License.
  15. (define-module (fibers timers)
  16. #:use-module (fibers scheduler)
  17. #:use-module (fibers operations)
  18. #:use-module (scheme time)
  19. #:export (sleep-operation
  20. timer-operation
  21. sleep))
  22. (define (timer-operation expiry)
  23. "Make an operation that will succeed when the current time is
  24. greater than or equal to @var{expiry}, expressed in internal time
  25. units. The operation will succeed with no values."
  26. (define (try-fn)
  27. (and (< expiry (current-jiffy))
  28. (lambda () (values))))
  29. (define (block-fn state resume)
  30. (schedule-task (lambda ()
  31. (when (op-state-complete! state)
  32. (resume (lambda () (values)))))
  33. (max 0 (- expiry (current-jiffy)))))
  34. (make-base-operation #f try-fn block-fn))
  35. (define (sleep-operation seconds)
  36. "Make an operation that will succeed with no values when
  37. @var{seconds} have elapsed."
  38. (define expiry
  39. (+ (current-jiffy)
  40. (inexact->exact (round (* seconds (jiffies-per-second))))))
  41. (timer-operation expiry))
  42. (define (sleep seconds)
  43. "Block the calling fiber until @var{seconds} have elapsed."
  44. (perform-operation (sleep-operation seconds)))