Scheduler.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Action } from './scheduler/Action';
  2. import { Subscription } from './Subscription';
  3. export interface IScheduler {
  4. now(): number;
  5. schedule<T>(work: (this: Action<T>, state?: T) => void, delay?: number, state?: T): Subscription;
  6. }
  7. /**
  8. * An execution context and a data structure to order tasks and schedule their
  9. * execution. Provides a notion of (potentially virtual) time, through the
  10. * `now()` getter method.
  11. *
  12. * Each unit of work in a Scheduler is called an {@link Action}.
  13. *
  14. * ```ts
  15. * class Scheduler {
  16. * now(): number;
  17. * schedule(work, delay?, state?): Subscription;
  18. * }
  19. * ```
  20. *
  21. * @class Scheduler
  22. */
  23. export class Scheduler implements IScheduler {
  24. public static now: () => number = Date.now ? Date.now : () => +new Date();
  25. constructor(private SchedulerAction: typeof Action,
  26. now: () => number = Scheduler.now) {
  27. this.now = now;
  28. }
  29. /**
  30. * A getter method that returns a number representing the current time
  31. * (at the time this function was called) according to the scheduler's own
  32. * internal clock.
  33. * @return {number} A number that represents the current time. May or may not
  34. * have a relation to wall-clock time. May or may not refer to a time unit
  35. * (e.g. milliseconds).
  36. */
  37. public now: () => number;
  38. /**
  39. * Schedules a function, `work`, for execution. May happen at some point in
  40. * the future, according to the `delay` parameter, if specified. May be passed
  41. * some context object, `state`, which will be passed to the `work` function.
  42. *
  43. * The given arguments will be processed an stored as an Action object in a
  44. * queue of actions.
  45. *
  46. * @param {function(state: ?T): ?Subscription} work A function representing a
  47. * task, or some unit of work to be executed by the Scheduler.
  48. * @param {number} [delay] Time to wait before executing the work, where the
  49. * time unit is implicit and defined by the Scheduler itself.
  50. * @param {T} [state] Some contextual data that the `work` function uses when
  51. * called by the Scheduler.
  52. * @return {Subscription} A subscription in order to be able to unsubscribe
  53. * the scheduled work.
  54. */
  55. public schedule<T>(work: (this: Action<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {
  56. return new this.SchedulerAction<T>(this, work).schedule(state, delay);
  57. }
  58. }