Skip to content

Instantly share code, notes, and snippets.

@kbravh
Last active March 26, 2023 17:14
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbravh/2ac6652b21e0f559ab883100cb1282ed to your computer and use it in GitHub Desktop.
Save kbravh/2ac6652b21e0f559ab883100cb1282ed to your computer and use it in GitHub Desktop.
Adjust cron events for DST (Daylight Savings Time) automatically with a Python function to be run on AWS Lambda.
from datetime import datetime
import pytz
import boto3
# define our CloudEvents client
client = boto3.client('events')
# Let's grab our current time in GMT and convert it to local time (US Central)
utc_time = datetime.utcnow().replace(tzinfo=pytz.utc)
# Set your timezone here! See timezones here: https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568
cst_timezone = pytz.timezone('US/Central')
cst_time = utc_time.astimezone(cst_timezone)
# This will show the offset in seconds for DST ⏰
# If it's zero, we're not in DST
is_dst = cst_time.tzinfo._dst.seconds != 0
# Determine our new cron expressions for a function running every day at 7am and 7pm CST
# Adjust these times to fit what you would like for during and after of DST
if is_dst:
start_schedule = 'cron(0 12 ? * * *)'
stop_schedule = 'cron(0 0 ? * * *)'
else:
start_schedule = 'cron(0 13 ? * * *)'
stop_schedule = 'cron(0 1 ? * * *)'
# Set the names of your AWS Event rules here
START_RULE = "start_rule"
STOP_RULE = "stop_rule"
# Fetch the targets of our current cron rules
start_settings = client.list_targets_by_rule(Rule=START_RULE)
stop_settings = client.list_targets_by_rule(Rule=STOP_RULE)
# Remove targets from current rules
client.remove_targets(
Rule=START_RULE,
Ids=[(start_settings['Targets'][0]['Id'])]
)
client.remove_targets(
Rule=STOP_RULE,
Ids=[(stop_settings['Targets'][0]['Id'])]
)
# Delete rules
client.delete_rule(Name=START_RULE)
client.delete_rule(Name=STOP_RULE)
# Add new rules
client.put_rule(
Name=START_RULE,
ScheduleExpression=start_schedule,
State='ENABLED',
Description="Automatic trigger for the function."
)
client.put_rule(
Name=STOP_RULE,
ScheduleExpression=stop_schedule,
State='ENABLED',
Description="Automatic trigger for the function"
)
# Add back our targets
client.put_targets(
Rule=START_RULE,
Targets=[
{
'Id': start_settings['Targets'][0]['Id'],
'Arn':start_settings['Targets'][0]['Arn'],
'Input': start_settings['Targets'][0]['Input']
}
]
)
client.put_targets(
Rule=STOP_RULE,
Targets=[
{
'Id': stop_settings['Targets'][0]['Id'],
'Arn':stop_settings['Targets'][0]['Arn'],
'Input': stop_settings['Targets'][0]['Input']
}
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment