Source code for google.appengine.api.background_thread.background_thread
#!/usr/bin/env python## Copyright 2007 Google Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.#"""Background Threads API.An API for creating background threads.Background threads created using this API do not inherit the context of theircreator and do not need to end before the creator request completes."""__all__=['start_new_background_thread','BackgroundThread','Error','FrontendsNotSupported','BackgroundThreadLimitReachedError',]importcollectionsimportsysimportthreadingfromgoogle.appengine.apiimportapiproxy_stub_mapfromgoogle.appengine.api.systemimportsystem_service_pbfromgoogle.appengine.runtimeimportapiproxy_errorsfromgoogle.appengine.runtimeimportbackground
[docs]classError(Exception):"""Base exception class for this module."""
[docs]classFrontendsNotSupported(Error):"""Error raised when a background thread is requested on a front end."""
[docs]classBackgroundThreadLimitReachedError(Error):"""Error raised when no further active background threads can be created."""
[docs]defstart_new_background_thread(target,args,kwargs=None):"""Starts a new background thread. Creates a new background thread which will call target(*args, **kwargs). Args: target: A callable for the new thread to run. args: Position arguments to be passed to target. kwargs: Keyword arguments to be passed to target. Returns: The thread ID of the background thread. """ifkwargsisNone:kwargs={}request=system_service_pb.StartBackgroundRequestRequest()response=system_service_pb.StartBackgroundRequestResponse()try:apiproxy_stub_map.MakeSyncCall('system','StartBackgroundRequest',request,response)exceptapiproxy_errors.ApplicationErroraserror:raiseERROR_MAP[error.application_error](error.error_detail)else:returnbackground.EnqueueBackgroundThread(response.request_id(),target,args,kwargs)
[docs]classBackgroundThread(threading.Thread):"""A threading.Thread-like interface for background threads."""
[docs]defstart(self):"""Starts this background thread."""ifnotself._Thread__initialized:raiseRuntimeError('thread.__init__() not called')ifself._Thread__started.is_set():raiseRuntimeError('threads can only be started once')withthreading._active_limbo_lock:threading._limbo[self]=selftry:start_new_background_thread(self.__bootstrap,())exceptException:withthreading._active_limbo_lock:delthreading._limbo[self]raiseself._Thread__started.wait()