使用 Kivy / python for android 的服务中的计划任务

问题描述

我想使用 Clock.schedule_interval(mycallback,dt) 在后台运行的服务中实现计划任务。当我在我的服务中实现这一点时,执行此行前后的代码但从未调用回调。就像代码被忽略了一样,我没有任何错误。 我阅读了许多论坛和文档,但没有找到任何内容。 感谢您的帮助!

我刚刚修改了我在这里找到的示例:https://github.com/tshirtman/kivy_service_osc

我的service.py

'p4a example service using oscpy to communicate with main application.'
from random import sample,randint
from string import ascii_letters
from time import localtime,asctime,sleep

from oscpy.server import OSCThreadServer
from oscpy.client import OScclient

from kivy.clock import Clock

CLIENT = OScclient('localhost',3002)


def ping(*_):
    'answer to ping messages'
    CLIENT.send_message(
        b'/message',[
            ''.join(sample(ascii_letters,randint(10,20)))
            .encode('utf8'),],)


def send_date(dt):
    'send date to the application'
    print('debug2')
    CLIENT.send_message(
        b'/date',[asctime(localtime()).encode('utf8'),)
   

if __name__ == '__main__':
    SERVER = OSCThreadServer()
    SERVER.listen('localhost',port=3000,default=True)
    SERVER.bind(b'/ping',ping)
    Clock.schedule_clock(send_date,1)    
    while True:
        sleep(1)
        print("debug")

解决方法

要获取错误并调试代码,请尝试

from random import sample,randint
from string import ascii_letters
from time import localtime,asctime,sleep

from oscpy.server import OSCThreadServer
from oscpy.client import OSCClient

from kivy.clock import Clock

CLIENT = OSCClient('localhost',3002)


def ping(*_):
    'answer to ping messages'
    CLIENT.send_message(
        b'/message',[
            ''.join(sample(ascii_letters,randint(10,20)))
            .encode('utf8'),],)



def send_date(dt):
 try:
    'send date to the application'
    print('debug2')
    CLIENT.send_message(
        b'/date',[asctime(localtime()).encode('utf8'),)
 except Exception as myerror:
  print(myerror)

if __name__ == '__main__':
    SERVER = OSCThreadServer()
    SERVER.listen('localhost',port=3000,default=True)
    SERVER.bind(b'/ping',ping)
    Clock.schedule_clock(send_date,1)    
    while True:
        sleep(1)
        print("debug")