在Ubuntu上實現分布式定時任務,通??梢允褂靡韵聨追N方法:
使用Cron結合分布式鎖:
使用Celery:
使用Apache Airflow:
使用Kubernetes CronJobs:
下面是一個簡單的示例,展示如何使用Cron結合Redis分布式鎖來實現分布式定時任務:
首先,安裝所需的軟件包:
sudo apt-get update
sudo apt-get install python3-pip redis-server
pip3 install redis
創建一個Python腳本distributed_cron.py
,內容如下:
import time
import redis
from datetime import datetime
# 連接到Redis服務器
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
def acquire_lock(lock_name, acquire_timeout=10):
identifier = str(uuid.uuid4())
end = time.time() + acquire_timeout
while time.time() < end:
if redis_client.setnx(lock_name, identifier):
return identifier
time.sleep(0.001)
return False
def release_lock(lock_name, identifier):
with redis_client.pipeline() as pipe:
while True:
try:
pipe.watch(lock_name)
if pipe.get(lock_name) == identifier:
pipe.multi()
pipe.delete(lock_name)
pipe.execute()
return True
pipe.unwatch()
break
except redis.WatchError:
pass
return False
def task():
print(f"Task executed at {datetime.now()}")
def main():
lock_name = "distributed_cron_lock"
identifier = acquire_lock(lock_name)
if identifier:
try:
task()
finally:
release_lock(lock_name, identifier)
else:
print("Failed to acquire lock")
if __name__ == "__main__":
main()
編輯Cron任務:
crontab -e
添加以下行來每分鐘運行一次腳本:
* * * * * /usr/bin/python3 /path/to/distributed_cron.py
確保Redis服務器正在運行:
sudo systemctl start redis-server
通過這種方式,你可以確保即使在多個節點上運行Cron任務,也只有一個節點能夠執行定時任務。