Skip to content

Instantly share code, notes, and snippets.

@GrahamDumpleton
Created October 19, 2012 01:49
Show Gist options
  • Save GrahamDumpleton/3915819 to your computer and use it in GitHub Desktop.
Save GrahamDumpleton/3915819 to your computer and use it in GitHub Desktop.
Tracking a one off task run from a script as a background job.
# Run this as:
#
# NEW_RELIC_CONFIG_FILE=newrelic.ini newrelic-admin run-python example.py
#
# If being run under Heroku, you can skip setting NEW_RELIC_CONFIG_FILE on the
# command line as the required environment variable settings added by the
# Heroku New Relic addon will be picked up automatically.
import time
import newrelic.agent
# This force registers the agent and waits for it to register for period up to
# that specified by timeout. If doesn't register in that time, execution will
# continue anyway.
#
# If this is being done as background thread to web process where agent is
# already running and in use, then you can comment out the line to register the
# agent.
#
# Instead of using register_application() here, could also set startup_timeout
# setting in agent configuration file, or use the NEW_RELIC_STARTUP_TIMEOUT
# environment variable. Using the environment variable would not be advisable
# on Heroku if this is being run in a web dyno as it will also affect the
# monitoring being done on the web application.
newrelic.agent.register_application(timeout=5.0)
start = time.time()
# Background decorator applied to function you want to track time spent in.
@newrelic.agent.background_task(name='Update', group='Tasks')
def do_update():
# ... do stuff
do_update()
# Force artificial delay to ensure that reporting period is at least one second
# otherwise data collector can throw away data, thinking it is invalid.
#
# This is not required if using version 1.7.0 of the agent or newer as those
# agent versions use a trick to ensure the reporting period satisfies the time
# threshold requirement if there are transactions recorded and process is being
# shutdown at that time.
finish = time.time()
duration = finish - start
if duration < 1.1:
time.sleep(1.1 - duration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment