Looking for "max execution time" option

Hi there,

I was wondering if it is possible to set a “max execution time” for a K6 test in Javascript.

There is this duration option

A string specifying the total duration a test run should be run for
During this time each VU will execute the script in a loop
Except as you can see it runs in a loop, which is not ideal for me.

I want my script to only run once, store the metrics and start again later (via cronjob or other means)

There is another option called iterations

A number specifying a fixed number of iterations to execute of the script, as opposed to specifying a duration of time during which the script would run in a loop.

But it looks like this would overwrite the duration option.

Is there any option that makes sure my script stops after X seconds, even if it is not yet finished (and ideally makes the test fail) ?

Hi @GerbenT,
If you combine duration and iterations, the test will finish which ever finishes first.

So you can specify duration and it will mean that this is the maximum the test can run for.

After [PR 1007]{https://github.com/loadimpact/k6/pull/1007/} is merged this will be somewhat more obvious as with the new configuration there is “maxDuration” :wink:

1 Like

As @mstoykov has pointed out, {iterations: 1, duration: "<your-max-duration>"}as the options would do what you want.

Failing the test is a bit trickier… I guess you can set a threshold for a counter metric that will fail the test if it’s not 1. You’d have to work around this bug, but that’s easy. The code can look somewhat like this:

import { sleep } from "k6";
import { Counter } from 'k6/metrics';

let iterations = new Counter('iterations');

export let options = {
    iterations: 1,
    duration: '10s', // max duration
    thresholds: {
        // fail the test if we don't have a single iteration
        'iterations': ['count==1']
    }
};
export default function () {
    iterations.add(0); // workaround for https://github.com/loadimpact/k6/issues/1346

    // Your test logic here, now just a random sleep between 5 and 15 seconds,
    // to see some test runs succeed and others fail :)
    sleep(5 + Math.random() * 10);
}
1 Like

Thank you both, this is exactly what i need.

Preferably i would like to see Checks being able to stop the execution of the test and provide an error code, because they can give more detail as to why the script has stopped (instead of the generic error message from the Thresholds "some thresholds have failed")

See https://k6.io/docs/using-k6/thresholds#aborting-a-test-when-a-threshold-is-crossed

Not currently possible, it’s a planned feature, follow https://github.com/loadimpact/k6/issues/680 and https://github.com/loadimpact/k6/issues/870 for updates