How to set delay in scheduled job for every run?

rkreddy
Giga Expert

Hi,

I am using a scheduled job in which I am getting the records from a table and performing action on every record in while loop. Now I want to set some delay for every iteration in while loop, how to achieve it?

var csa = new GlideRecord('cmdb_ci_cloud_service_account');
csa.addEncodedQuery('datacenter_type!=null');
csa.query();
while(csa.next()){
var scheduleConfig = new global.CloudDiscoveryScheduleConfig();
var accountSysId = csa.sys_id + '';
var result = {};
try {
	result = scheduleConfig.discoverDatacenters(accountSysId);
} catch(err) {
	result.error = err;
}
	
}

Thanks

1 ACCEPTED SOLUTION

we do nothing in that while as it will just iterate for 10 seconds

That's how the delay would be generated

If my response helped you please mark it correct to close the question so that it benefits future readers as well.

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

8 REPLIES 8

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

gs.sleep() is not recommended and won't work in scoped app

use this to give some 10 seconds delay in while loop

var csa = new GlideRecord('cmdb_ci_cloud_service_account');
csa.addEncodedQuery('datacenter_type!=null');
csa.query();
while(csa.next()){

	// wait for 10 seconds
	var seconds = parseInt(10, 10) * 1000;
	var start = parseInt(new Date().getTime()) + seconds;
	while(start>parseInt(new Date().getTime())){
		// do nothing
	}

	var scheduleConfig = new global.CloudDiscoveryScheduleConfig();
	var accountSysId = csa.sys_id + '';
	var result = {};
	try {
		result = scheduleConfig.discoverDatacenters(accountSysId);
	} catch(err) {
		result.error = err;
	}

}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi @Ankur Bawiskar ,

Thank you. Could you please explain a little bit about using the below lines in the script. Don't we do anything in this while loop?

while(start>parseInt(new Date().getTime())){
		// do nothing
	}

we do nothing in that while as it will just iterate for 10 seconds

That's how the delay would be generated

If my response helped you please mark it correct to close the question so that it benefits future readers as well.

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi @Ankur Bawiskar ,

Thank you. Will use this.