What I'm trying to do is to run multiple threads at some starting time. Those threads must stay alive for 90minutes after start. During the 90minutes they execute something after a random sleep time (ex: 5minutes to 15minutes).
Here is a pseudo code on how I would implement it. The problem is that doing it in this way the threads run in an unexpected way.
How can I implement correctly something like this?
Class MyJob {
static triggers = {
cron name: 'first', cronExpression: "0 30 21 * * FRI"
cron name: 'second', cronExpression: "0 30 19 * * FRI"
cron name: 'third', cronExpression: "0 30 17 * * FRI"
def myService
def execute() {
switch( between trigger name )
case 'first':
model = Model.findByAttribute(...)
...
myService.run( model, start_time )
break;
...
}
}
class MyService {
def run( model, start_time ) {
def end_time = end_time.plusMinutes(90)
model.fields.each( field -> Thread.start { executeSomeTasks( field, start_time, end_time ) } )
}
def executeSomeTasks( field, start_time, end_time ) {
while( start_time < end_time ) {
...do something ...
sleep( Random.nextInt( 1000 ) );
}
}
}