js_periodic
The `js_periodic` directive allows you to configure periodic JavaScript execution within the context of a stream server in NGINX.
Description
The js_periodic directive is part of the NGINX njs dynamic modules, enabling the execution of JavaScript functions at specified intervals. This directive works within the context of a stream server, allowing developers to perform actions at regular intervals without needing to handle this in an external application or service.
When using js_periodic, developers can specify how often a particular JavaScript function should be executed by providing an interval value. The implementation supports additional parameters, such as jitter, to customize the execution timing for load balancing and other operational needs. The directive leverages the NJS runtime to execute the JavaScript function asynchronously, ensuring that the server remains responsive even while performing scheduled tasks.
Typically, the behavior encompasses setting up an event loop that triggers the specified JavaScript code, which can then carry out operations such as monitoring health checks, performing actions based on server state, or any user-defined logic that should run periodically. This makes it especially useful for scenarios where background processing or scheduled tasks are required without blocking the main server flow.
Config Example
stream {
server {
listen 12345;
js_periodic 5000; # Executes every 5 seconds
# additional configuration
}
}Ensure the defined JavaScript function does not block the main event loop.
Consider server load, as frequent execution could affect performance if the interval is too short.
Make sure to handle asynchronous operations properly within the JavaScript logic.