【发布时间】:2017-12-11 22:31:33
【问题描述】:
从在 apscheduler 中运行的作业中在 sqlite3 中插入值时遇到问题。
我正在寻找一种从作业中插入值的方法。我想这意味着从主机线程运行作业?或者填充缓冲区并将其汇集到管理 sql 事务的单个线程?
处理此问题的最佳方法是什么?我计划稍后在烧瓶应用程序中运行它。
代码如下:
"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""
from datetime import datetime
import time
import os
from apscheduler.schedulers.background import BackgroundScheduler
def tick():
print('Tick! The time is: %s' % datetime.now())
def tick1():
print('Tick1! The time is: %s' % datetime.now())
id = "testId"
global sql_cursor
sql_cursor.execute("INSERT INTO histories VALUES(?,?,?)", (datetime.now(),id,0.0))
if __name__ == '__main__':
import sqlite3
sql_db = sqlite3.connect('histories.db')
sql_cursor = sql_db.cursor()
sql_cursor.execute(
'''CREATE TABLE IF NOT EXISTS histories(
timestamp DATE, id TEXT, value REAL)''')
sql_db.commit()
scheduler = BackgroundScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
scheduler.start()
scheduler.add_job(tick1, 'interval', seconds=1)
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()
还有错误:
Tick1! The time is: 2017-12-11 22:22:59.232296
Job "tick1 (trigger: interval[0:00:01], next run at: 2017-12-11 22:22:59 UTC)" raised an exception
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/apscheduler/executors/base.py", line 125, in run_job
retval = job.func(*job.args, **job.kwargs)
File "background.py", line 20, in tick1
sql_cursor.execute("INSERT INTO histories VALUES(?,?,?)", (datetime.now(),id,0.0))
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id -1225585456 and this is thread id -1260391312
【问题讨论】:
-
为什么要使用在另一个线程中创建的游标对象?您是否尝试在您真正需要的地方创建连接(=tick1)?当然也可以在同一个地方提交
-
我现在就试试这个。连续快速连接和创建光标有问题吗?
标签: python python-3.x flask sqlite apscheduler