python 远程调度进程服务与客户端

核心思想: 在本地或远程机器上创建一个进程,提供调度服务。使用了 APScheduler。

安装:APScheduler

$ wget https://pypi.python.org/packages/89/52/22f11f5ca425f16409797c5c651de380824a252acd1ced4ef1ee54507bbf/APScheduler-3.1.0.tar.gz#md5=fae7e2a06a5f4b608599bf8b237bb40a
$ python2.7 setup.py build
$ python2.7 setup.py install

测试:
$ python2.7 -c "from apscheduler.schedulers.blocking import BlockingScheduler"

服务端:

#!/usr/bin/python2.7
#-*- coding: UTF-8 -*-
#
#   apsserver.py
#
# Refer:
#   http://www.cnblogs.com/Xjng/p/4902514.html
#
# Queues are thread and process safe.
# Refer:
#   https://docs.python.org/2/library/multiprocessing.html
#
########################################################################
# The MIT License (MIT)
#    http://opensource.org/licenses/MIT
#
#  Copyright (c) 2015 copyright cheungmine
#
# Permission is hereby granted, free of charge, to any person obtaining
#  a copy of this software and associated documentation files (the
#  "Software"), to deal in the Software without restriction, including
#  without limitation the rights to use, copy, modify, merge, publish,
#  distribute, sublicense, and/or sell copies of the Software, and to
#  permit persons to whom the Software is furnished to do so, subject
#  to the following conditions:
#
# The above copyright notice and this permission notice shall be
#  included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
########################################################################

import os, time, datetime

from multiprocessing.managers import BaseManager
from multiprocessing import RLock

# aps
from apscheduler.schedulers.background import BackgroundScheduler
import logging
logging.basicConfig()

# global variables
#
lock = RLock()

scheduler = BackgroundScheduler()
scheduler.start()

class APSchedulerManager(BaseManager): pass

def tick():
    print('Tick! The time is: %s' % datetime.datetime.now())

# thread safe class
#
class APSchedulerConnectProxy(object):
    global scheduler

    def AddJob(self, config):
        print("AddJob: %s" % config)
        return scheduler.add_job(tick, 'interval', seconds=3)

    def Start(self):
        scheduler.start()

    def Shutdown(self, wait):
        scheduler.shutdown()

###########################################################
#
class APSchedulerManagerServer:
    APSchedulerManager.register('get_lock', callable=lambda: lock)
    APSchedulerManager.register('APSchedulerConnect', APSchedulerConnectProxy)

    def __init__(self, host, port, passkey):
        self.manager = APSchedulerManager(address=(host, port), authkey=passkey)
        self.server = self.manager.get_server()
        pass

    def start(self):
        self.server.serve_forever()
        pass

    def stop(self):
        self.server.shutdown()
        self.is_stop = 1
        pass

###########################################################
# start_apserver('', 12345, 'abc')
#
def start_apserver(host, port, passkey):
    from apsserver import APSchedulerManagerServer
    server = APSchedulerManagerServer(host, port, passkey)
    server.start()

###########################################################
# main
if __name__ == "__main__":
    from apsserver import APSchedulerManagerServer

    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        start_apserver('', 12345, 'abc')
    except (KeyboardInterrupt, SystemExit):
        print('\nUser has pressed Ctrl+Break')
    finally:
        pass

客户端:

#!/usr/bin/python2.7
#-*- coding: UTF-8 -*-
#
#   apsclient.py
#
# Refer:
#   http://www.cnblogs.com/Xjng/p/4902514.html
#
# Queues are thread and process safe.
# Refer:
#   https://docs.python.org/2/library/multiprocessing.html
#
########################################################################
# The MIT License (MIT)
#    http://opensource.org/licenses/MIT
#
#  Copyright (c) 2015 copyright cheungmine
#
# Permission is hereby granted, free of charge, to any person obtaining
#  a copy of this software and associated documentation files (the
#  "Software"), to deal in the Software without restriction, including
#  without limitation the rights to use, copy, modify, merge, publish,
#  distribute, sublicense, and/or sell copies of the Software, and to
#  permit persons to whom the Software is furnished to do so, subject
#  to the following conditions:
#
# The above copyright notice and this permission notice shall be
#  included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
########################################################################

from multiprocessing.managers import BaseManager
from multiprocessing import RLock

# aps
from apscheduler.schedulers.background import BackgroundScheduler
import logging
logging.basicConfig()

class APSchedulerConnectProxy(object): pass

class APSchedulerManager(BaseManager): pass

class APSchedulerManagerClient:
    APSchedulerManager.register('get_lock', callable=lambda: lock)
    APSchedulerManager.register('APSchedulerConnect', callable=lambda: APSchedulerConnectProxy)

    def __init__(self, servhost, servport, authkey):
        self.config = {
            "host": servhost,
            "port": int(servport),
            "authkey": authkey
        }

        self._lock = None
        self.manager = APSchedulerManager(address=(self.config['host'], self.config['port']), authkey=self.config['authkey'])
        self.manager.connect()
        pass

    def __del__(self):
        self.unlock()
        pass

    def lock(self):
        if not self._lock:
            self._lock = self.manager.get_lock()
            self._lock.acquire()
        pass

    def unlock(self):
        if self._lock:
            l = self._lock
            self._lock = None
            l.release()
        pass

    def getAPSchedulerConnect(self):
        self.apschedulerConn = self.manager.APSchedulerConnect()
        return self.apschedulerConn

###########################################################
# connect_apserver('', 12345, 'abc')
#
def connect_apserver(host, port, passkey):
    from apsclient import APSchedulerManagerClient

    client = APSchedulerManagerClient(host, port, passkey)

    print "connect to apsserver success"

    apschedulerConn = client.getAPSchedulerConnect()
    apschedulerConn.AddJob("hello apsserver")

###########################################################
# main
if __name__ == "__main__":
    import os

    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        connect_apserver('', 12345, 'abc')
    except (KeyboardInterrupt, SystemExit):
        print('\nUser has pressed Ctrl+Break')
    finally:
        pass

启动服务端与客户端。服务端输出:

./apsserver.py
Press Ctrl+C to exit
AddJob: hello apsserver
Tick! The time is: 2016-04-26 17:38:02.899242
Tick! The time is: 2016-04-26 17:38:05.899450
Tick! The time is: 2016-04-26 17:38:08.899632
Tick! The time is: 2016-04-26 17:38:11.900290

python 远程调度进程服务与客户端的更多相关文章

  1. python网络编程TCP服务多客户端的服务端开发

    #服务多客户端TCP服务端开发 2 #方法说明 3 """ 4 bind(host,port)表示绑定端口号,host是ip地址,ip地址一般不进 行绑定,表示本机的任何 ...

  2. 远程计算机 进程/服务 启动停止(WMI)

    WMI的远程管理需要其计算机的本地管理员组权限,例:gwmi win32_computersystem -computer win08r2d #在远程计算机上启动 notepad.exe 进程invo ...

  3. python 并发编程 socket 服务端 客户端 阻塞io行为

    阻塞io行为 server.accept server.recv client.send recv,accept  分为两个阶段 1.wait for data 对方把数据经过网络延迟送到自己的操作系 ...

  4. vscode连接云服务,搭建Python远程开发

    配置Python远程开发环境前提 配置步骤 1.windows 10 开发机配置 win10 1809后支持ssh ssh-keygen -t rsa -b 4096 #会显示生成到的目录C:\Use ...

  5. Python异常处理和进程线程-day09

    写在前面 上课第九天,打卡: 最坏的结果,不过是大器晚成: 一.异常处理 - 1.语法错误导致的异常 - 这种错误,根本过不了python解释器的语法检测,必须在程序运行前就修正: - 2.逻辑上的异 ...

  6. python之路-进程

    博客园 首页 新随笔 联系 管理 订阅 随笔- 31  文章- 72  评论- 115    python之路——进程   阅读目录 理论知识 操作系统背景知识 什么是进程 进程调度 进程的并发与并行 ...

  7. python 操作系统和进程

    一. 操作系统介绍 多道程序系统 多道程序设计技术       所谓多道程序设计技术,就是指允许多个程序同时进入内存并运行.即同时把多个程序放入内存,并允许它们交替在CPU中运行,它们共享系统中的各种 ...

  8. Python 操作系统介绍 进程的创建

    背景知识 顾名思义,进程即正在执行的一个过程.进程是对正在运行程序的一个抽象. 进程的概念起源于操作系统,是操作系统最核心的概念,也是操作系统提供的最古老也是最重要的抽象概念之一.操作系统的其他所有内 ...

  9. python之路——进程

    操作系统背景知识 顾名思义,进程即正在执行的一个过程.进程是对正在运行程序的一个抽象. 进程的概念起源于操作系统,是操作系统最核心的概念,也是操作系统提供的最古老也是最重要的抽象概念之一.操作系统的其 ...

随机推荐

  1. Python Django缓存,信号,序列化,文件上传,Ajax登录和csrf_token验证

    本节内容 models操作 Django的缓存 请求方式 序列化 Form 配合Ajax实现登录认证 上传文件 Ajax  csrf_token验证方式 1 models操作 单表查询: curd(增 ...

  2. 面试题2:实现Singleton模式

    题目:设计一个类,我们只能生成该类的一个实例.

  3. mysql常见的优化需要注意的点

    1.explain分析explian引用索引基数show indexes from table_name;主键索引具有最好的基数 测试时 不走缓存SELECT SQL_NO_CACHE id from ...

  4. samba服务器配置过程

    SAMBA服务器配置 yum install samba samba-client samba-swat 改变文件权限及用户 vi /etc/samba/smb.conf d+G全删注释 复制下面代码 ...

  5. linux tar解压命令

    linux下使用tar命令 解压语法:tar [主选项+辅选项] 文件或者目录 使用该命令时,主选项是必须要有的,它告诉tar要做什么事情,辅选项是辅助使用的,可以选用.主选项:c 创建新的档案文件. ...

  6. 转:Socket原理与编程基础

    from: http://acm.tzc.edu.cn/acmhome/projectList.do?method=projectNewsDetail&nid=2 一.Socket简介 Soc ...

  7. FJUT寒假作业第三周数蚂蚁(记录第一道并查集)

    http://210.34.193.66:8080/vj/Contest.jsp?cid=162#P7 思路:用并查集合并集合,最后遍历,找到集合的根的个数. 并查集是森林,森林中的每一颗树是一个集合 ...

  8. Linux shell查询ip归属地

    起因 有的时候写脚本需要能够在脚本中获取到ip的归属地,比如分析登录日志列出攻击者的相关信息等. 可以使用whois来查询ip的详细信息,但是whois并不是每台机器预装的,而且我想看中文的结果,所以 ...

  9. Linux下使用MD5加密BASE64加密

    这里以字符串123456为例子,它的md5密文值为:e10adc3949ba59abbe56e057f20f883e 这里以1.txt为需要被加密的文件. 一. 用oppnssl md5 加密字符串和 ...

  10. PHP 实例 AJAX RSS 阅读器

    RSS 是一种描述和同步网站内容的格式,是目前使用最广泛的XML应用. RSS 搭建了信息迅速传播的一个技术平台,使得每个人都成为潜在的信息提供者. RSS 阅读器用于阅读 RSS Feed. AJA ...