Skip to content

Commit

Permalink
feat(tasks): add repeat task
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed Apr 9, 2021
1 parent 1404baf commit 67db390
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/tasks/schedule/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './repeat';
export * from './sleep';
export * from './timeout';
26 changes: 26 additions & 0 deletions src/tasks/schedule/repeat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Task } from '../../definitions';
import { run } from '../../utils/run';
import { isCancelled } from '../../utils/is-cancelled';
import { series } from '../aggregate/series';
import { log } from '../stdio/log';

/**
* Run `task` for `times` repetitions,
* or indifinitely otherwise.
* @returns Task
*/
export function repeat(times: number | null, task: Task): Task.Async {
return series(
log('debug', 'Task repetition set at', times, 'times'),
async (ctx) => {
let i = 0;
const isDone = (): boolean => times !== null && times >= 0 && i >= times;

while (!isDone()) {
i++;
if (await isCancelled(ctx)) break;
await run(series(log('debug', 'Repeat task:', i), task), ctx);
}
}
);
}
2 changes: 1 addition & 1 deletion src/tasks/schedule/timeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function timeout(
return ms < 0
? series(log('debug', 'Timeout disabled:', ms), task)
: series(
log('debug', 'Task timeout set at', ms),
log('debug', 'Task timeout set at', ms, 'milliseconds'),
create(async (ctx) => {
const altTask = alternate || raises('Task timeout');
if (ms <= 0) return altTask;
Expand Down

0 comments on commit 67db390

Please sign in to comment.