logo
down
shadow

How to exit/terminate a job earlier and handle the raised exception in apscheduler?


How to exit/terminate a job earlier and handle the raised exception in apscheduler?

Content Index :

How to exit/terminate a job earlier and handle the raised exception in apscheduler?
Tag : python , By : m0gb0y74
Date : November 27 2020, 03:01 PM

To fix the issue you can do Don't ever, ever use sys.exit within a job. Raise exceptions instead. If you don't want APScheduler to handle exceptions, handle them yourself before APScheduler.
I assume you are using a ThreadPool executor (which is the default). Within a thread, sys.exit raises a SystemExit error. This is what APScheduler caught according to your logs, this is 100% normal. APScheduler will always try to catch and log any exception coming from your job (to avoid loosing the underlying thread/process). Even a sys.exit(0) is abnormal in a job: APScheduler expects you to end the job by letting the job's function return without throwing any exception.
class StopJob(BaseException):
    pass

def print_header():
    if not proc_is_running(DB['process_name']):
        raise StopJob('DB process <{0}> is NOT running.'.format(DB['process_name']))

    log.info('{:=^70}'.format('='))

def make_db_snapshot(dataset, args):
    try:
        do_stuff(dataset, args)
        print_headers()
        do_other_stuff()
    except StopJob:
        logger.exception('Stopping job.')
        # APScheduler won't notice the exception because it is handled, but it will be logged anyways.

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?


Tag : python , By : user116330
Date : March 29 2020, 07:55 AM
Does that help You can call os._exit() to directly exit, without throwing an exception:
import os
os._exit(1)

Setting exit code in Python when an exception is raised


Tag : python , By : damomurf
Date : March 29 2020, 07:55 AM
Any of those help Take a look at the traceback module. You could do the following:
import sys, traceback

try:
  raise Exception()
except:
  traceback.print_exc()
  sys.exit(3)

How to handle a custom exception raised inside an exception handler?


Tag : python , By : user107506
Date : March 29 2020, 07:55 AM
seems to work fine Once an exception gets caught by an except clause, any subsequent excepts in the same block are ignored, so you can't do that:
try:
   ...
except Something:
   raise MyError
except MyError: <-- won't work!
  ....
try:

    try:
       ...
    except Something:
       raise MyError

except MyError: <-- will work
   ...
try:
  raise CustomIOError
except IOError: <-- works
  pass
# higher-level code

class UserInterface:

     def writeButtonClick:
        try:
            readAndWrite()
        except ReadAndWriteFailure:
            showMessage("Problem! Please try again") 

# lower-level code

class ReadAndWriteFailure(Exception):
    pass

def readAndWrite():
   try:
       fp = open(someFile)
       db = sql.connection()
       for line in fp:
          db.execute(line)
   except IOError:
      log it
      raise ReadAndWriteFailure()
   except SQLError:
      log it
      raise ReadAndWriteFailure()
   etc

How to efficiently exit a python program if any exception is raised/caught


Tag : python , By : rajiv
Date : March 29 2020, 07:55 AM
it should still fix some issue Say I have a block of exception statements: , One thing you could do is:
flag = False

try:
    expression
    flag = True
except err1:
    #process error
    ...
    ...
except err10:
    #process error
if not flag:
    sys.exit(1) #exit program

kazoo DataWatch does not exit the program when exception is raised


Tag : python , By : user185939
Date : March 29 2020, 07:55 AM
should help you out DataWatch is run in a separate thread and there are specific ways to kill the main process from a thread, see Why does sys.exit() not exit when called inside a thread in Python?
Something like os._exit() does work.
Related Posts Related QUESTIONS :
  • Retrieve Variable From Class
  • What is the reason for matplotlib for printing labels multiple times?
  • Why would people use ThreadPoolExecutor instead of direct function call?
  • When clear_widgets is called, it doesnt remove screens in ScreenManager
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com