parent
b02acc1a14
commit
e4863d89ca
@ -0,0 +1,12 @@
|
||||
import os # Get abs path of the file
|
||||
# Create CMD str to run file if process.exe is not running
|
||||
def ProcessStartIfNotRunning(inProcessName, inFilePath):
|
||||
lFileAbsPath = os.abspath(inFilePath)
|
||||
lResult = f'tasklist /nh /fi "imagename eq {inProcessName}" | find /i "{inProcessName}" > nul || (start {lFileAbsPath})'
|
||||
return lResult
|
||||
# Create CMD str to stop process
|
||||
def ProcessStop(inProcessName, inFlagForceClose)
|
||||
lResult = f'taskkill /im "{inProcessName}" /fi "username eq %USERNAME%"'
|
||||
if inFlagForceClose:
|
||||
lResult+= " /F"
|
||||
return lResult
|
@ -0,0 +1,17 @@
|
||||
from . import CMDStr # Create CMD Strings
|
||||
from . import Connector # RDP API
|
||||
def ProcessStartIfNotRunning(inGlobalDict, inSessionIndex, inProcessName, inFilePath):
|
||||
lCMDStr = CMDStr.ProcessStartIfNotRunning(inProcessName,inFilePath)
|
||||
# Calculate the session Hex
|
||||
lSessionHex = inGlobalDict["RDPList"][inSessionIndex]["SessionHex"]
|
||||
# Run CMD
|
||||
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="RUN")
|
||||
# Create CMD str to stop process
|
||||
def ProcessStop(inGlobalDict, inSessionIndex, inProcessName, inFlagForceClose)
|
||||
lCMDStr = f'taskkill /im "{inProcessName}" /fi "username eq %USERNAME%"'
|
||||
if inFlagForceClose:
|
||||
lCMDStr+= " /F"
|
||||
# Calculate the session Hex
|
||||
lSessionHex = inGlobalDict["RDPList"][inSessionIndex]["SessionHex"]
|
||||
# Run CMD
|
||||
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="RUN")
|
@ -0,0 +1,106 @@
|
||||
from . import Timer # Async thread
|
||||
import threading # Create in another thread
|
||||
import datetime # Datetime class
|
||||
import copy # Copy struct functions
|
||||
import time # time functions
|
||||
import importlib # import lib functions
|
||||
# Scheduler class - init and work by the configuration
|
||||
# OOP
|
||||
class Scheduler:
|
||||
# Class properties
|
||||
mSchedulerDict = None
|
||||
#########################
|
||||
# Init class
|
||||
def __init__(self,inSchedulerDict):
|
||||
self.Init(inSchedulerDict = inSchedulerDict)
|
||||
# Init the class instance
|
||||
def Init(self,inSchedulerDict):
|
||||
self.mSchedulerDict = inSchedulerDict
|
||||
# Init the threads
|
||||
lTimerMainThread = threading.Thread(target = self.TimerMainThreadRun)
|
||||
lTimerMainThread.start() # Start the Timer main thread
|
||||
print (f"Class instance configuration: {self.mSchedulerDict}, Init has been completed")
|
||||
########################
|
||||
# Main timer thread - run when init class instance
|
||||
def TimerMainThreadRun(self):
|
||||
lDaemonStartDateTime=datetime.datetime.now()
|
||||
lDaemonLoopSeconds=self.mSchedulerDict["ActivityTimeCheckLoopSeconds"]
|
||||
lDaemonActivityLogDict={} #Словарь отработанных активностей, ключ - кортеж (<activityType>, <datetime>, <processPath || processName>, <processArgs>)
|
||||
#Вечный цикл
|
||||
while True:
|
||||
lCurrentDateTime = datetime.datetime.now()
|
||||
#Циклический обход правил
|
||||
lFlagSearchActivityType=True
|
||||
for lIndex, lItem in enumerate(self.mSchedulerDict["ActivityTimeList"]):
|
||||
#Проверка дней недели, в рамках которых можно запускать активность
|
||||
lItemWeekdayList=lItem.get("WeekdayList", [0, 1, 2, 3, 4, 5, 6])
|
||||
if lCurrentDateTime.weekday() in lItemWeekdayList:
|
||||
if lFlagSearchActivityType:
|
||||
#######################################################################
|
||||
#Branch 1 - if has TimeHH:MM
|
||||
#######################################################################
|
||||
if "TimeHH:MM" in lItem:
|
||||
#Вид активности - запуск процесса
|
||||
#Сформировать временной штамп, относительно которого надо будет проверять время
|
||||
#часовой пояс пока не учитываем
|
||||
lActivityDateTime=datetime.datetime.strptime(lItem["TimeHH:MM"],"%H:%M")
|
||||
lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day)
|
||||
#Убедиться в том, что время наступило
|
||||
if (
|
||||
lActivityDateTime>=lDaemonStartDateTime and
|
||||
lCurrentDateTime>=lActivityDateTime and
|
||||
(lIndex,lActivityDateTime) not in lDaemonActivityLogDict):
|
||||
#Выполнить операцию
|
||||
#Запись в массив отработанных активностей
|
||||
lDaemonActivityLogDict[(lIndex,lActivityDateTime)]={"ActivityStartDateTime":lCurrentDateTime}
|
||||
#Запустить процесс - new code
|
||||
#################
|
||||
#Call function from Activity structure
|
||||
################################################
|
||||
lSubmoduleFunctionName = lItem["Activity"]["DefName"]
|
||||
lFileFullPath = lItem["Activity"]["ModulePath"] # "path\\to\\module.py"
|
||||
lModuleName = (lFileFullPath.split("\\")[-1])[0:-3]
|
||||
lTechSpecification = importlib.util.spec_from_file_location(lModuleName, lFileFullPath)
|
||||
lTechModuleFromSpec = importlib.util.module_from_spec(lTechSpecification)
|
||||
lTechSpecificationModuleLoader = lTechSpecification.loader.exec_module(lTechModuleFromSpec)
|
||||
if lSubmoduleFunctionName in dir(lTechModuleFromSpec):
|
||||
# Run SettingUpdate function in submodule
|
||||
#mGlobalDict = getattr(lTechModuleFromSpec, lSubmoduleFunctionName)()
|
||||
getattr(lTechModuleFromSpec, lSubmoduleFunctionName)(*lItem["Activity"]["ArgList"],**lItem["Activity"]["ArgDict"])
|
||||
#################################################
|
||||
#######################################################################
|
||||
#Branch 2 - if TimeHH:MMStart, TimeHH:MMStop, ActivityIntervalSeconds
|
||||
#######################################################################
|
||||
if "TimeHH:MMStart" in lItem and "TimeHH:MMStop" in lItem and "ActivityIntervalSeconds" in lItem:
|
||||
#Сформировать временной штамп, относительно которого надо будет проверять время
|
||||
#часовой пояс пока не учитываем
|
||||
lActivityDateTime=datetime.datetime.strptime(lItem["TimeHH:MMStart"],"%H:%M")
|
||||
lActivityDateTime=lActivityDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day)
|
||||
lActivityTimeEndDateTime=datetime.datetime.strptime(lItem["TimeHH:MMStop"],"%H:%M")
|
||||
lActivityTimeEndDateTime=lActivityTimeEndDateTime.replace(year=lCurrentDateTime.year,month=lCurrentDateTime.month,day=lCurrentDateTime.day)
|
||||
#Убедиться в том, что время наступило
|
||||
if (
|
||||
lCurrentDateTime<lActivityTimeEndDateTime and
|
||||
lCurrentDateTime>=lActivityDateTime and
|
||||
(lIndex,lActivityDateTime) not in lDaemonActivityLogDict):
|
||||
#Запись в массив отработанных активностей
|
||||
lDaemonActivityLogDict[(lIndex,lActivityDateTime)]={"ActivityStartDateTime":lCurrentDateTime}
|
||||
#Call function from Activity structure
|
||||
################################################
|
||||
lSubmoduleFunctionName = lItem["Activity"]["DefName"]
|
||||
lFileFullPath = lItem["Activity"]["ModulePath"] # "path\\to\\module.py"
|
||||
lModuleName = (lFileFullPath.split("\\")[-1])[0:-3]
|
||||
lTechSpecification = importlib.util.spec_from_file_location(lModuleName, lFileFullPath)
|
||||
lTechModuleFromSpec = importlib.util.module_from_spec(lTechSpecification)
|
||||
lTechSpecificationModuleLoader = lTechSpecification.loader.exec_module(lTechModuleFromSpec)
|
||||
if lSubmoduleFunctionName in dir(lTechModuleFromSpec):
|
||||
# Run SettingUpdate function in submodule
|
||||
#mGlobalDict = getattr(lTechModuleFromSpec, lSubmoduleFunctionName)()
|
||||
lDef = getattr(lTechModuleFromSpec, lSubmoduleFunctionName) #(*lItem["Activity"]["ArgList"],**lItem["Activity"]["ArgDict"])
|
||||
#################################################
|
||||
#Запуск циклической процедуры
|
||||
#Timer.activityLoopStart(lItem["ActivityIntervalSeconds"], lActivityTimeEndDateTime, lItem["Activity"])
|
||||
lTimer = Timer.RepeatedTimer(lItem["ActivityIntervalSeconds"], lActivityTimeEndDateTime, lDef, *lItem["Activity"]["ArgList"], **lItem["Activity"]["ArgDict"]) # it auto-starts, no need of rt.start()
|
||||
#Уснуть до следующего прогона
|
||||
print (f"Loop has been completed")
|
||||
time.sleep(lDaemonLoopSeconds)
|
@ -0,0 +1,31 @@
|
||||
from threading import Timer
|
||||
import datetime
|
||||
class RepeatedTimer(object):
|
||||
def __init__(self, interval, inDateTimeEnd, function, *args, **kwargs):
|
||||
self._timer = None
|
||||
self.interval = interval
|
||||
self.function = function
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.is_running = False
|
||||
self.mDateTimeEnd = inDateTimeEnd # DateTime when stop
|
||||
self.start()
|
||||
def _run(self):
|
||||
self.is_running = False
|
||||
lResultGoLoop=True
|
||||
lCurrentDateTime=datetime.datetime.now()
|
||||
self.function(*self.args, **self.kwargs)
|
||||
if lCurrentDateTime>=self.mDateTimeEnd:
|
||||
lResultGoLoop=False
|
||||
if lResultGoLoop is not None:
|
||||
if lResultGoLoop:
|
||||
self.start()
|
||||
def start(self):
|
||||
if not self.is_running:
|
||||
self._timer = Timer(self.interval, self._run)
|
||||
self._timer.start()
|
||||
self.is_running = True
|
||||
|
||||
def stop(self):
|
||||
self._timer.cancel()
|
||||
self.is_running = False
|
@ -0,0 +1,39 @@
|
||||
from pyOpenRPA.Tools.RobotRDPActive import Scheduler
|
||||
inConfiguration={
|
||||
"ActivityTimeCheckLoopSeconds":5, #Количество секунд, между циклами проверки действий
|
||||
"ActivityTimeList": [
|
||||
{
|
||||
"TimeHH:MM": "22:23", #Time [HH:MM] to trigger activity
|
||||
"WeekdayList": [1,2,3,4,5,6,7], #List of the weekday index when activity is applicable, Default [1,2,3,4,5,6,7]
|
||||
"Activity":{
|
||||
"ModulePath": "Session\\SessionDefs.py", # "Session\\SessionDefs.py"
|
||||
"DefName":"test", # Function name
|
||||
"ArgList":[1,2,3], # Args list
|
||||
"ArgDict":{"ttt":1,"222":2,"dsd":3} # Args dictionary
|
||||
}
|
||||
},
|
||||
{
|
||||
"TimeHH:MM": "14:17", #Time [HH:MM] to trigger activity
|
||||
"WeekdayList": [1, 2, 3], #List of the weekday index when activity is applicable, Default [1,2,3,4,5,6,7]
|
||||
"Activity":{
|
||||
"ModulePath": "Session\\SessionDefs.py", # "Session\\SessionDefs.py"
|
||||
"DefName":"test", # Function name
|
||||
"ArgList":[1,2,3], # Args list
|
||||
"ArgDict":{"ttt":1,"222":2,"dsd":3} # Args dictionary
|
||||
}
|
||||
},
|
||||
{
|
||||
"TimeHH:MMStart": "12:40", #Time [HH:MM] to trigger activity
|
||||
"TimeHH:MMStop": "14:36",
|
||||
"ActivityIntervalSeconds": 2,
|
||||
"WeekdayList": [1, 2, 3, 4, 5, 6, 7], #List of the weekday index when activity is applicable, Default [1,2,3,4,5,6,7]
|
||||
"Activity":{
|
||||
"ModulePath": "Session\\SessionDefs.py", # "Session\\SessionDefs.py"
|
||||
"DefName":"test", # Function name
|
||||
"ArgList":[1,2,3], # Args list
|
||||
"ArgDict":{"ttt":1,"222":2,"dsd":3} # Args dictionary
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
lT = Scheduler.Scheduler(inConfiguration)
|
Loading…
Reference in new issue