10 lines of code to implement a duty reminder application

10 lines of code to implement a duty reminder application

picture 1

At work, we often encounter application scenarios where team members need to be scheduled and reminded on duty. Although there are some ready-made apps that can be used, it is tedious for programmers to use and may not be flexible.

So, how do we create a simple on-duty scheduling and reminder application?picture 2

Consider a simple case where the following assumptions are made about the constraints:

  • The duty sequence is fixed, once it is determined, it will not be modified
  • Each person is on duty for a fixed time, for example: each person is on duty for a week

The requirements are assumed as follows:

  • At the right time, remind the person on duty the duty time
  • Remind the person on duty and predict the next person on duty

The constraints and requirements are translated into code as follows:


on_duty_list = ['孙悟空', '沙和尚', '猪八戒', '白龙马'] # 值班人列表
on_duty_period_in_days = 7 # 每人值一周
notify_days = [1, 5] # 假设值班第一天提醒一次,第5天再提醒一次
# 第一个值班人值班开始时间
on_duty_first_person = '孙悟空'
on_duty_first_day = '2022-03-24 00:00:00'
# 提醒消息模板
notify_template = Template(r"""
【===========报警值班提醒========】
【本周值班人】${on_duty_person_this_week}
【值班时间】 ${on_duty_range}
【下周值班人】${on_duty_person_next_week}
""")
复制代码

How to use the program to calculate who should be on duty at the current time?

Simple mathematical calculations are used here: integer division, remainder operation

Divide the time difference between the current time and the start time of the first person on duty by 7 days to get how many weeks have passed, and then take the remainder of the number of people on duty to get the number of people on duty that should be currently on duty.

def WhoIsOnDuty(timeTs = int(time.time())):
    ref_timeTs = UnixTimeFromDate(on_duty_first_day)
    deltaTs = timeTs - ref_timeTs
    deltaDay = deltaTs / oneDayTs
    index = deltaDay / on_duty_period_in_days % len(on_duty_list)
    return on_duty_list[index]
复制代码

How to calculate the duty time range?

This involves simple date calculations, using the datetime library

def WhoIsOnDuty(timeTs = int(time.time())):
    ref_timeTs = UnixTimeFromDate(on_duty_first_day)
    deltaTs = timeTs - ref_timeTs
    deltaDay = deltaTs / oneDayTs
    index = deltaDay / on_duty_period_in_days % len(on_duty_list)
    day_index = deltaDay % on_duty_period_in_days
    ts = time.localtime(timeTs)
    start_day = str(datetime.date(ts.tm_year, ts.tm_mon, ts.tm_mday) + datetime.timedelta(days = -day_index))
    end_day = str(datetime.date(ts.tm_year, ts.tm_mon, ts.tm_mday) + datetime.timedelta(days = - day_index + on_duty_period_in_days - 1))
    return on_duty_list[index], day_index + 1, start_day, end_day, on_duty_list[(index+1)%len(on_duty_list)]
复制代码

These 10 lines of code are the core of the entire application.

The entire application code is as follows:

#!/usr/bin/env python
# coding: utf-8

import time
from string import Template
import datetime

on_duty_list = ['孙悟空', '沙和尚', '猪八戒', '白龙马']
on_duty_period_in_days = 7 # day
notify_days = [1, 5]
on_duty_first_person = '孙悟空'
on_duty_first_day = '2022-03-24 10:00:00'
oneDayTs = 24 * 60 * 60

notify_template = Template(r"""
【===========报警值班提醒========】
【本周值班人】${on_duty_person_this_week}
【值班时间】 ${on_duty_range}
【下周值班人】${on_duty_person_next_week}
""")

def SendMessage(message='test'):
    print message

def PairListToMessage(pair_list):
    conent_arr = []
    for k, v in pair_list:
        conent_arr.append(' '.join(['【' + k + '】', v]))
    return '\n'.join(conent_arr)

def UnixTimeFromDate(time_str, format='%Y-%m-%d %H:%M:%S'):
    # 先转换为时间数组
    timeArray = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    # 转换为时间戳
    timeStamp = int(time.mktime(timeArray))
    return timeStamp

def DatetimeStr(timeTs, format='%Y-%m-%d %H:%M:%S'):
    return time.strftime(format, time.localtime(timeTs))

def WhoIsOnDuty(timeTs = int(time.time())):
    ref_timeTs = UnixTimeFromDate(on_duty_first_day)
    deltaTs = timeTs - ref_timeTs
    deltaDay = deltaTs / oneDayTs
    index = deltaDay / on_duty_period_in_days % len(on_duty_list)
    day_index = deltaDay % on_duty_period_in_days
    ts = time.localtime(timeTs)
    start_day = str(datetime.date(ts.tm_year, ts.tm_mon, ts.tm_mday) + datetime.timedelta(days = -day_index))
    end_day = str(datetime.date(ts.tm_year, ts.tm_mon, ts.tm_mday) + datetime.timedelta(days = - day_index + on_duty_period_in_days - 1))
    return on_duty_list[index], day_index + 1, start_day, end_day, on_duty_list[(index+1)%len(on_duty_list)]


# 周四、每周一提醒本周值班人员,下周值班人员
notify_counter = 0
on_duty_person_this_week = ''
While True:
    timeTs = int(time.time())
    timeStr = DatetimeStr(timeTs)
    on_duty_person, day, start_day, end_day, on_duty_person_next = WhoIsOnDuty(timeTs)
    if on_duty_person != on_duty_person_this_week:
        on_duty_person_this_week = on_duty_person
        notify_counter = 0
        SendMessage(notify_template.safe_substitute({
            'on_duty_person_this_week': on_duty_person,
            'on_duty_person_next_week': on_duty_person_next,
            'on_duty_range': '~'.join([start_day, end_day]),
        }))
        notify_counter += 1
    else:
        if notify_counter < 2 and day in notify_days:
            SendMessage(notify_template.safe_substitute({
                'on_duty_person_this_week': on_duty_person,
                'on_duty_person_next_week': on_duty_person_next,
                'on_duty_range': '~'.join([start_day, end_day]),
            }))
            notify_counter += 1
    time.sleep(1)
复制代码

The effect is as follows:picture 1

Here is a thought question for readers, welcome to exchange in the comment area.

  • How to realize the function of temporary shift shift?
  • Call third-party APIs to implement such as official account reminders, SMS reminders, etc.

If you think the article is helpful to you, you can follow the WeChat public account: Small and Beautiful Practical Python to get more fresh articles.

Guess you like

Origin juejin.im/post/7079930918894305294