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. bzoj4559[JLoi2016]成绩比较 容斥+拉格朗日插值法

    4559: [JLoi2016]成绩比较 Time Limit: 20 Sec  Memory Limit: 256 MBSubmit: 261  Solved: 165[Submit][Status ...

  2. 使用JAXB解析xml文件(一)

      1.java中解析xml的几种方式 1.1 JDK原生dom形式 原理:一次性把xml读入内存,在内存中构建成树形结构.优点:对节点操作方便,缺点:需要大量的内存空间,浪费资源 1.2 SAX形式 ...

  3. SVN提交时显示:Path is not a working copy directory

    说明你地址没有checkout啊 先checkout,才能add和commi. 要是在一个已有的项目出现这个错误,就是包含这个地址的文件夹没添加进去,去上一层再试一次. 总之,养成在项目根目录提交的习 ...

  4. JavaScript判断不同平台

    function getPlatformType() { let UA = navigator.userAgent; if(/MicroMessenger/i.test(UA)){ return 'w ...

  5. 保留键的情况下取字典中最大的值(max\zip函数的联合使用)

    在我们平常想要获取字典中value最大或者最小的值的时候,常常使用如下函数: testDict = {"age1":18,"age2":20,"age ...

  6. SpringMVC 教程 - Handler Method

    原文链接:https://www.codemore.top/cates/Backend/post/2018-04-21/spring-mvc-handler-methods 由注解@RequestMa ...

  7. dephi FillChar 的几种写法

    //在 delphi 新版中, char 已经是双字节了.故应该重新自己写一个函数,取名为 FillByte ,才无歧义. procedure TForm1.Button2Click(Sender: ...

  8. JS中的DOM— —节点以及操作

    DOM操作在JS中可以说是非常常见了吧,很多网页的小功能的实现,比如一些元素的增删操作等都可以用JS来实现.那么在DOM中我们需要知道些什么才能完成一些功能的实现呢?今天这篇文章就先简单的带大家入一下 ...

  9. jQuery 学习笔记一

  10. swing JTable 更新数据

    rowData 是将要更新的表格内数据,coloumnName是将要更新的表头数据. table是原本的table对象,更新数据的时候要用 DefaultTableModel 类~ /*更新table ...