#!/usr/bin/env python # -*- coding: utf-8 -*- import json import logging import os import time from os.path import dirname, abspath import requests PROJECT_DIR = dirname(dirname(dirname(abspath(__file__)))) print PROJECT_DIR import sys sys.path.insert(0, PROJECT_DIR) if len(sys.argv) > 1: if sys.argv[1] == 'pro': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings_pro") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings_test") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings_test") import django from django.conf import settings ''' Django 版本大於等於1.7的時候,須要加上下面兩句 import django django.setup() 不然會拋出錯誤 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. ''' if django.VERSION >= (1, 7): # 自動判斷版本 django.setup() logger = logging.getLogger('bss') pidfile = 'logs/bss.pid' def clean(): try: logger.info('刪除鎖文件%s', pidfile) if os.path.exists(pidfile): os.remove(pidfile) logger.info('刪除鎖文件%s成功', pidfile) return 1 except Exception as e: msg = "刪除鎖文件%s失敗" % e logger.error(msg, exc_info=True) return 0 def lock(): try: logger.info('建立鎖文件%s', pidfile) file(pidfile, 'w+').write('%s\n' % os.getpid()) logger.info('建立鎖文件%s成功', pidfile) except Exception as e: msg = "建立鎖文件%s失敗" % e logger.error(msg, exc_info=True) sys.exit(0) class BssService(object): def __init__(self): self.period_url = settings.BILLING_ALL_URL def build(self): logger.info("billing task begin>>>>>>>>>>>>>>>>>>") # do something logger.info("billing task end>>>>>>>>>>>>>>>>>>") if __name__ == "__main__": if not os.path.exists(pidfile): lock() bs = BssService() bs.build() status = clean() n = 10 while status == 0 and n > 0: time.sleep(1) status = clean() n -= 1 else: logger.info("其餘進程正在執行!")