You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy/Python for Android后台服务中Clock定时任务不触发如何解决

问题原因与解决方案

核心问题1:API调用错误

你代码中调用的Clock.schedule_clock是不存在的方法,如果你要实现固定间隔重复触发回调,正确的API是Clock.schedule_interval(callback, interval)。

核心问题2:事件循环被阻塞

Kivy的Clock调度依赖Kivy主事件循环驱动才能运行,你代码末尾的无限while True循环配合time.sleep()会完全阻塞当前线程,Kivy事件循环没有任何运行机会,就算修正了API调用,回调也不会触发。

修复后的可用代码

'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

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

from kivy.clock import Clock
from kivy.base import runTouchApp

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'), ],
    )

def debug_print(dt):
    print("debug")

if __name__ == '__main__':
    SERVER = OSCThreadServer()
    SERVER.listen('localhost', port=3000, default=True)
    SERVER.bind(b'/ping', ping)
    # 修正API调用
    Clock.schedule_interval(send_date,1)
    # 原来的循环打印逻辑也用Clock调度实现
    Clock.schedule_interval(debug_print, 1)
    # 启动Kivy事件循环
    runTouchApp()

额外说明

  • OSCThreadServer本身是在独立线程运行的,不会被Kivy事件循环阻塞,原有ping消息响应逻辑不受影响
  • 如果不需要显示Kivy界面,runTouchApp()可以无参数运行,仅驱动事件循环即可

内容的提问来源于stack exchange,提问作者Corentin Lorgerie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 12:27:03