If you want finer-grained control than maxschlepzig's nice bash incantations, it's a reasonably easy thing to just code up:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char**argv){
useconds_t mdelay=0, delay;
if (argc<3){
fprintf(stderr,"%s <delay (in milli-seconds)> <command> <args>* :\n\trun commands with a random delay\n",argv[0]);
exit(1);
}
mdelay=atol(argv[1]);
/* seed random number generator with the time */
srand(((unsigned int)time(NULL))%RAND_MAX);
delay = mdelay * (rand() / (1.0 + RAND_MAX));
usleep(delay*1000);
execvP(argv[2],getenv("PATH"),argv+2);
return 0;
}
Compile with something like gcc randomdelay.c -o randomdelay and invoke it like
$ randomdelay 10000 echo Hi!
If you are doing this is a programming context you might be better off just grabbing the part of the code that picks the random delay for you and calls an exec family function (which one you want depends on exactly how you have it specified internally).
Issue here:
- This assumes your systems
rand/srand are sane (not good PRNGs mind you just that they do what the man page says they do). I've been having some trouble with it on my Mac OS X box, where those functions are deprecated in favor of random/srandom.
- Historically, many implementation of
rand have had poor numeric characteristics. That shouldn't be a problem in this application, but if it is, replace it with a better PRNG.
- The command line argument handling in this toy is a bit primitive.
- The delay is chosen uniformly from some range. For some applications you might prefer an unbounded distribution like an exponential. Stack Overflow has many questions on how to get non-uniform distributions from a uniform PRNGs.