useScheduleTaskRunCallback
The useScheduleTaskRunCallback
hook returns a function that can be used to schedule a specific task in the Manager
provided by a Provider
component.
useScheduleTaskRunCallback(
taskId: string,
arg?: string,
startAfter?: number,
config?: TaskRunConfig,
configDeps?: DependencyList,
): () => Id | undefined
Type | Description | |
---|---|---|
taskId | string | The |
arg? | string | An optional string argument to pass to the |
startAfter? | number | A timestamp at, or duration after which, the task should run. |
config? | TaskRunConfig | An optional |
configDeps? | DependencyList | An optional array of dependencies for the config object, which, if any change, result in the callback being regenerated. Defaults to an empty array. |
returns | () => Id | undefined | A callback that will return the new unique |
The hook returns a callback. When called, the task will be executed with the optional string argument provided, and can be configured to start at a specific time (TimestampMs
), or after a specific delay (DurationMs
).
You can also provide a custom TaskRunConfig
which lets you indicate the duration of the task run and its retry behaviors, for example.
The callback will return a unique Id
for the scheduled task run. However, if the Manager
is in the stopping state, new task runs can not be scheduled, and in that case, the method will return undefined
.
Example
This example shows how to use the useScheduleTaskRunCallback
hook within a component that's nested inside a Provider. The hook is used to create a callback that will schedule a task in response to a click event.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createManager} from 'tinytick';
import {Provider, useScheduleTaskRunCallback} from 'tinytick/ui-react';
const Pane = () => {
const handleClick = useScheduleTaskRunCallback('log');
return (
<span id="span" onClick={handleClick}>
Log
</span>
);
};
const App = ({manager}) => (
<Provider manager={manager}>
<Pane />
</Provider>
);
const manager = createManager().start();
manager.setTask('log', async () => console.log('Task ran'));
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App manager={manager} />);
const span = app.querySelector('span');
console.log(span.innerHTML);
// -> 'Log'
// User clicks the <span> element:
// -> span MouseEvent('click', {bubbles: true})
// ... wait 100ms for task to start running
// -> 'Task ran'
Since
v1.2.0