最近在写一些Steem相关的程序,也遇到了一些技术方面的问题。其中一个主要问题就是由于Steem网络的不稳定,导致程序不能按时完成指定的任务。而程序又是设定的cron job,比如:每5分钟就会自动执行一次。那么如果上一次程序因为Steem网络问题没有结束,而下一次的运行又开始了。在极端情况下,就会有很多个进程同时运行,不仅占用更多的系统内存,而且也为Steem区块链网络带来不必要的流量,比如:两个进程如果同时upvote同一篇文章,那么有一个其实做的就是无效工作,但却给区块链网络带来了不必要的负担。下面提供一个简单的办法来解决这个问题。核心点其实就是在调用相应的方法时,设定一个执行时限,到时候如果没有完成的话,就要强制退出。
I have recently written some Steem-related scripts and encountered some technical problems. One of the main problems is due to the instability of the Steem network, sometimes the program can not finish on time. Since the script is configured as a cron job, if the current execution of the script cannot complete on time, there might be multiple instances of the same script running at the same. In this case, they will not only take up more system memory, but also bring unnecessary traffic to the Steem block chain network. The following code provides an easy way to solve this problem.
Image source: pixabay.com
好了,看代码吧:
Here is the code:
import signal
import time
timeout_interval = 5
def steem_timeout_handler(signum, frame):
print ("Cannot get response from Steem network!")
raise Exception("Steem network timeout")
def steem_op():
# write your steem code here ...
while True:
print (".")
time.sleep(1)
signal.signal(signal.SIGALRM, steem_timeout_handler)
signal.alarm(timeout_interval)
try:
steem_op()
except Exception as ex:
print (ex)
上面的演示程序并没有真正的调用Steem API,而是用一个循环进行了简单的模拟。运行效果如下:
The output is:
$ python test.py
.
.
.
.
.
Cannot get response from Steem network!
Steem network timeout
至此,问题已经解决,你所需要的就是设置一个对你的程序来说比较合理的timeout_interval。
Problem solved.
https://steemit.com 首发。非常感谢阅读,欢迎FOLLOW, Resteem和Upvote @yuxi 激励我创作更多更好的内容。