[英]How to limit google script execution time to 1 minute?
How do I set a time limit to end a function from running after 1 minute?如何设置时间限制以在 1 分钟后结束运行?
Situation: i have a script that runs every 5 mins every day.情况:我有一个每天每 5 分钟运行一次的脚本。 My scripts are exceeding the daily computing time limit of 3 hours.我的脚本超过了每天 3 小时的计算时间限制。
So, I need to make a function that calls calls my functon A (very long so i won post it here), but only lets it run for 1 minute maximum, then ends.所以,我需要创建一个函数来调用我的函数 A(很长,所以我把它贴在这里),但只让它运行最多 1 分钟,然后结束。
I have searched extensively but all the other solutions work with loops.我已经进行了广泛的搜索,但所有其他解决方案都使用循环。 My functon that is causing the timeout however is not a loop kind of function.但是,导致超时的函数不是循环函数。 I dont mind the function not being successfully completing.我不介意该功能没有成功完成。
You either need a loop, executing short sections of code that only run for a few seconds at a time;你要么需要一个循环,执行一次只运行几秒钟的一小段代码; or you'll need to add multiple lines of code that check the status every "so often".或者您需要添加多行代码,以“经常”检查状态。
To get the start time, you could use:要获取开始时间,您可以使用:
var startTime = Date.now(); //Get milliseconds from a date in past
As a test, you can run the following function, and then View the Logs:作为测试,您可以运行以下函数,然后查看日志:
function exampleCode() {
var startTime = Date.now();
Logger.log(startTime);
Utilities.sleep(1000); //Stop the code for 1 second
var timeNow = Date.now();
Logger.log(timeNow);
var elapsedTime = timeNow - startTime;
Logger.log(elapsedTime);
};
Of course, you wouldn't want to ever re-assign the startTime
.当然,您不会想要重新分配startTime
。 So put that at the top of your code, and don't ever re-calculate it.所以把它放在代码的顶部,永远不要重新计算它。
To stop the code, at 1 minute, that's 60000 milliseconds停止代码,在 1 分钟,即 60000 毫秒
if (elapsedTime > 60000) {return}; //Quit after 1 minute
You could create a function to check the elapsed time:您可以创建一个函数来检查经过的时间:
function elapsedTime() {
var timeNow = Date.now();
var elapsedTime = timeNow - startTime;
if (elapsedTime > 60000) {return 'die'}; //return 'die' if longer than 1 minute
};
if (elapsedTime() === 'die') {return};//Quit after 1 minute
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.