Ejemplo n.º 1
0
def test_read_nonexistring_calendar(capsys):
    sch = Scheduler()
    with pytest.raises(Exception) as excinfo:
        sch.read_calendar(file='non_existring_file.extension')
    cp = capsys.readouterr()
    assert not cp.out
    assert 'No such file or directory:' in str(excinfo.value)
Ejemplo n.º 2
0
class Bot:
    def __init__(self):
        self.commands = Commands().initialize()
        self.scheduler = Scheduler().initialize()

    def start(self):
        self.scheduler.start()
        self.commands.start()
Ejemplo n.º 3
0
def test_read_empty_calendar(capsys):
    sch = Scheduler()
    with pytest.raises(Exception) as excinfo:
        sch.read_calendar(file='tests/empty.ics')
    cp = capsys.readouterr()
    assert not cp.out
    assert 'Multiple calendars in one file are not supported by this method.' in str(
        excinfo.value)
Ejemplo n.º 4
0
def test_load_some_events_calendar(capsys):
    sch = Scheduler()
    sch.load_calendar(calendar_file='tests/some_events.ics')
    events = sch.get_events()
    p = capsys.readouterr()
    cp = capsys.readouterr()
    assert not cp.out
    assert not cp.err
    assert events
Ejemplo n.º 5
0
def init(bot: Bot, u: Updater):
    global updater
    updater = u
    global scheduler
    scheduler = Scheduler(database, updater)

    for user in database.users:
        for name in database.reqs[user]:
            if database.reqs[user][name]['enabled']:
                scheduler.start(user, name)
Ejemplo n.º 6
0
def main():
    """
    调度器入口
    :return:
    """
    s = Scheduler()
    s.run()
    print('------------------------------------>')
    print('欢迎使用nj_cookies_pool, 调度器开始运行……')
    print('------------------------------------>')
Ejemplo n.º 7
0
def schedule(n: str, kilo_playouts: str):
    try:
        n = int(n)
    except ValueError:
        n = None

    try:
        kilo_playouts = int(kilo_playouts)
    except ValueError:
        kilo_playouts = None
    scheduler = Scheduler()
    scheduler.schedule(n, kilo_playouts)
Ejemplo n.º 8
0
def main():

    if options.num_hours:
        try:
            hours = int(options.num_hours)
        except:
            print("Must enter a valid number of hours")
            return
    else:
        hours = 4

    scheduler = Scheduler(hours)
    scheduler.print_schedule()
Ejemplo n.º 9
0
    def start_scheduling(self, chosen_scheduler):
        """
        Start the scheduling thread so the window doesnt freeze
        param - {int} - chosen_scheduler- short variable for the scheduler, look in consts
        """
        # Start Scheduliung progress; is a class even necessary? dont know
        self.thread_handler = QThreadPool()

        scheduler = Scheduler(self, chosen_scheduler)
        self.thread_handler.start(scheduler)
Ejemplo n.º 10
0
def add_event():
    """Adds event to scheduler."""
    for atr in ['name', 'when', 'how']:
        if atr not in request.get_json():
            abort(400)
    
    if not verify_signature(request):
        abort(400)

    json = request.get_json()
    event = Scheduler.create_event(name=json.get('name'), when=json.get('when'), how=json.get('how'),  receiver=json.get('receiver'), message=json.get('message'), subject=json.get('subject'))
    sch.process_event(event)

    return '', 200
Ejemplo n.º 11
0
def run_scheduler():
    """Loads calendar and stars scheduler"""
    sch = Scheduler()
    try:
        sch.load_calendar(os.environ['CALENDAR'])
    except:
        pass

    sch.run()
    return sch
Ejemplo n.º 12
0
def process_msg(q):
    """
    从消息队列中取出消息进行处理,检查消息队列时间为0.5s
    """
    s = Scheduler()
    while True:
        if q.empty():
            time.sleep(0.5)
        else:
            msg = q.get()
            try:
                t = Thread(target=s.execute_cmd, args=(msg, ))
                t.start()
            except Exception as e:
                logger.error(e.args)
                s.c.send_text('({}) 执行失败,失败原因:{}'.format(msg, e.args))
Ejemplo n.º 13
0
def test_process_mail(capsys):
    sch = Scheduler()
    event = Scheduler.create_event('test', '2221-01-30 19:25:00', how='mail')

    sch.process_event(event)

    events = sch.get_events()
    p = capsys.readouterr()
    cp = capsys.readouterr()
    assert not cp.out
    assert not cp.err
    assert events
Ejemplo n.º 14
0
def create_scheduler_with_jobs():
    scheduler = Scheduler()
    datetime_now = datetime.datetime.now()
    job_a_time = datetime_now + datetime.timedelta(minutes=10)
    job_b_time = datetime_now + datetime.timedelta(minutes=15)
    job_c_time = datetime_now + datetime.timedelta(minutes=7)
    job_d_time = datetime_now + datetime.timedelta(minutes=19)
    job_e_time = datetime_now + datetime.timedelta(minutes=4)
    job_a_hours, job_a_minutes = job_a_time.hour, job_a_time.minute
    job_b_hours, job_b_minutes = job_b_time.hour, job_b_time.minute
    job_c_hours, job_c_minutes = job_c_time.hour, job_c_time.minute
    job_d_hours, job_d_minutes = job_d_time.hour, job_d_time.minute
    job_e_hours, job_e_minutes = job_e_time.hour, job_e_time.minute
    scheduler.register_job(job_a, str(job_a_hours) + ":" + str(job_a_minutes))
    scheduler.register_job(job_b, str(job_b_hours) + ":" + str(job_b_minutes))
    scheduler.register_job(job_c, str(job_c_hours) + ":" + str(job_c_minutes))
    scheduler.register_job(job_d, str(job_d_hours) + ":" + str(job_d_minutes))
    scheduler.register_job(job_e, str(job_e_hours) + ":" + str(job_e_minutes))
    return scheduler
Ejemplo n.º 15
0
def test_process_sms(capsys):
    sch = Scheduler()
    event = Scheduler.create_event('test', '2221-01-30 19:25:00', how='SMS')

    with pytest.raises(Exception) as excinfo:
        sch.process_event(event)

    events = sch.get_events()
    p = capsys.readouterr()
    cp = capsys.readouterr()
    assert not cp.out
    assert not cp.err
    assert not events
Ejemplo n.º 16
0
def test_new_task():
    """Validate NewTask system call create new task in scheduler"""
    bucket = []

    def child():
        for i in range(5):
            bucket.append(i)
            yield i

    def parent():
        _ = yield NewTask(child())

    scheduler = Scheduler()
    scheduler.new(parent())
    scheduler.mainloop()

    assert bucket == [0, 1, 2, 3, 4]
Ejemplo n.º 17
0
def test_get_tid():
    """Validate GetTid system call returns task id"""
    tids = []

    def _foo():
        mytid = yield GetTid()
        tids.append(mytid)
        for i in range(5):
            yield i

    scheduler = Scheduler()
    scheduler.new(_foo())
    scheduler.new(_foo())
    scheduler.mainloop()

    # can we do better than hard code?
    assert tids == [4, 5]
Ejemplo n.º 18
0
def test_wait_for_io():
    """Validate ReadWait/WriteWait wait for file descriptor to be available"""
    bucket = []
    file_obj = None

    def read():
        bucket.append(0)
        yield ReadWait(file_obj)
        bucket.append(1)

    def write():
        bucket.append(2)
        yield WriteWait(file_obj)
        bucket.append(3)

    with open('README.md', 'a+') as handler:
        file_obj = handler

        scheduler = Scheduler()
        scheduler.new(read())
        scheduler.new(write())
        scheduler.mainloop()

    assert bucket == [0, 2, 1, 3]
Ejemplo n.º 19
0
def hello(name, time, rest, mode, conf, color):
    """The Pomodoro Technique is a time management method developed by Francesco Cirillo in the late 1980s. The technique uses a timer to break down work into intervals, traditionally 25 minutes in length, separated by short breaks."""
    tasks = get_tasks_conf(conf)
    # default
    if not name and not time and not rest and not mode:
        tomatos = farm(tasks)
        manager = Scheduler(tomatos, color=color, isRandom=True)
    # single task
    if name is not None:
        if name in tasks:
            task = tasks[name]
            tom = Tomato(task["time"], task["rest"], name, task["content"])
        else:
            print("The task name is not in configuration file. Please input description and create temporary tasks for you.")
            description = input("task description:")
            tom = Tomato(time, rest, name, description)
        manager = Scheduler([tom], color=color, isRandom=False)
    # mode choice
    if name is None:
        tomatos = farm(tasks)
        isRandom = True if mode == "random" else False
        manager = Scheduler(tomatos, color=color, isRandom=isRandom)

    manager.next()
Ejemplo n.º 20
0
def test_simple_multitask():
    """Validate multitask scheduling by Scheduler"""
    bucket = []

    def _foo():
        for i in range(10):
            bucket.append(i)
            yield

    scheduler = Scheduler()
    scheduler.new(_foo())
    scheduler.new(_foo())
    scheduler.mainloop()

    expect_bucket = []
    for i in range(10):
        expect_bucket.append(i)
        expect_bucket.append(i)
    assert bucket == expect_bucket
Ejemplo n.º 21
0
def test_wait_for_task():
    """Validate WaitFor system call wait for child task to finish"""
    end_flag = int(uuid1())
    bucket = []

    def child():
        for i in range(5):
            bucket.append(i)
        yield i

    def parent():
        new_tid = yield NewTask(child())
        yield WaitTask(new_tid)
        bucket.append(end_flag)

    scheduler = Scheduler()
    scheduler.new(parent())
    scheduler.mainloop()

    # child task should finish and end flag should be
    # added to the end of the list
    expect_bucket = [0, 1, 2, 3, 4]
    expect_bucket.append(end_flag)
    assert bucket == expect_bucket
Ejemplo n.º 22
0
def test_kill_task():
    """Validate KillTask system call kill right task"""
    bucket = []

    def child():
        for i in range(5):
            bucket.append(i)
            yield i

    def parent():
        new_tid = yield NewTask(child())
        # kill non existed task
        success = yield KillTask(100000)
        assert success is False
        # kill existed task
        success = yield KillTask(new_tid)
        assert success is True

    scheduler = Scheduler()
    scheduler.new(parent())
    scheduler.mainloop()

    # child coroutine stops at first iteration
    assert bucket == [0, 1]
Ejemplo n.º 23
0
import RPi.GPIO as GPIO
import time, threading, requests, json, sys
from env_setup import ENV_API_URL, ENV_LOCATION_ID
from src.pin_setup import PinSetup
from src.config import Config, initConfig
from src.scheduler import Scheduler, initSchedule
from src.temperature import Temperature, initTemp
from src.furnace import Furnace

GPIO.setmode(GPIO.BCM)

# ~~~~~~~~ INIT THERMOSTAT DEPENDENCIES ~~~~~~~~
pins = PinSetup()
config = Config(initConfig)
furnace = Furnace(pins)
scheduler = Scheduler(initSchedule, config.chipId)
temperature = Temperature(initTemp, pins)


class Thermostat:
    def __init__(self):
        self.running = True
        self.prevTime = int(time.time())
        GPIO.add_event_detect(pins.runTestPin,
                              GPIO.RISING,
                              callback=self.ioRunToggle,
                              bouncetime=500)

    def ioRunToggle(self):
        self.running = False
Ejemplo n.º 24
0

def open_ui():
    eel.init('web')
    eel.start('index.html', port=8686)


def run_systray_icon():
    icon = pystray.Icon('test name')
    icon.title = APP_NAME
    icon.icon = Image.open(resource_path('src/icon.png'))
    icon.menu = pystray.Menu(
        pystray.MenuItem(text='Options', action=open_ui, default=True),
        pystray.MenuItem(text='Next photo', action=Options.set_wallpaper_next),
        pystray.MenuItem(text='Previous photo',
                         action=Options.set_wallpaper_prev),
        pystray.MenuItem(text='Random photo',
                         action=Options.set_wallpaper_random))

    icon.run()


if __name__ == '__main__':
    print('running')
    time.sleep(1)

    Scheduler.start()
    # 	# ui = threading.Thread(target = open_ui)
    # 	# ui.start()
    run_systray_icon()
Ejemplo n.º 25
0
 def __init__(self):
     self.commands = Commands().initialize()
     self.scheduler = Scheduler().initialize()
Ejemplo n.º 26
0
def test_create_event_with_wrong_date(capsys):
    with pytest.raises(Exception) as excinfo:
        Scheduler.create_event('test', 'test')
    cp = capsys.readouterr()
    assert not cp.out
    assert 'Could not match input to any of' in str(excinfo.value)
Ejemplo n.º 27
0
def main(args):
    scheduler = Scheduler(simulation_speed=args.simulation_speed)
    scheduler.run(run_time=args.simulation_time)
Ejemplo n.º 28
0
def simulate(scheduling_algorithm, accounting_file, verbose=False):
    ## Create Nodes
    if verbose:
        sys.stderr.write("Creating nodes ...\n")
    slow1 = ComputeNode(name='slow1', running_watts=SLOW_NODE_1_RUNNING_WATTS,
                        idle_watts=SLOW_NODE_1_IDLE_WATTS,
                        cpus=SLOW_NODE_1_CPUS, cost_per_kwh=DOLLARS_PER_KILOWATT_HOUR,
                        verbose=verbose)
    slow2 = ComputeNode(name='slow2', running_watts=SLOW_NODE_2_RUNNING_WATTS,
                        idle_watts=SLOW_NODE_2_IDLE_WATTS,
                        cpus=SLOW_NODE_2_CPUS, cost_per_kwh=DOLLARS_PER_KILOWATT_HOUR,
                        verbose=verbose)
    fast = ComputeNode(name='fast', running_watts=FAST_NODE_RUNNING_WATTS,
                        idle_watts=FAST_NODE_IDLE_WATTS,
                        cpus=FAST_NODE_CPUS, cost_per_kwh=DOLLARS_PER_KILOWATT_HOUR,
                        verbose=verbose)
    nodes = [slow1, slow2, fast]

    ## Read submission data into a list
    if verbose:
        sys.stderr.write("Reading job submission data into memory ...\n")
    jobs = jobs_from_accounting_file(accounting_file)
    if not jobs:
        sys.stderr.write("Failed to read accounting file " + accounting_file +\
                            "; exiting.\n")
        sys.exit()
    sys.stderr.write("Got " + str(len(jobs)) + " jobs.\n")

    period_of_study_begin = jobs[0].arrival_time

    ## Create Scheduler
    if verbose:
        sys.stderr.write("Creating scheduler ...\n")
    scheduler = Scheduler(scheduling_algorithm, nodes, jobs, verbose)

    ## Run simulation
    if verbose:
        sys.stderr.write("Initializing scheduler ...\n")
    scheduler.initialize(period_of_study_begin)
    if verbose:
        sys.stderr.write("Beginning simulation ...\n")
    current_second = period_of_study_begin

    while scheduler.jobs_remaining():
        if verbose and current_second % 3600 == 0:
            hours_elapsed = int((current_second - period_of_study_begin) / 3600)
            sys.stderr.write(str(hours_elapsed) + " sim hours elapsed ...\n")
            sys.stderr.write("scheduler has " + str(scheduler.jobs_remaining()) +
                            " jobs remaining\n")
        scheduler.update(current_second)
        current_second += 1

    period_of_study_end = current_second
    period_of_study_duration = period_of_study_end - period_of_study_begin

    ## Report results
    # print simulation info
    sim_start = date_string_from_epoch_timestamp(period_of_study_begin)
    sim_end = date_string_from_epoch_timestamp(period_of_study_end)
    sim_length = date_string_from_duration_in_seconds(period_of_study_duration)
    print("\n## SIMULATION INFORMATION ##\n")
    print("simulation start: " + sim_start)
    print("simulation end: " + sim_end)
    print("simulation duration (dd:hh:mm:ss): " + sim_length + "\n")

    # print job info
    print("\n## JOB INFORMATION ##\n")
    print("arrival_time\tstart_time\tcompletion_time\twait_time (dd:hh:mm:ss)\t" +
            "run_time (dd:hh:mm:ss)\tnode")
    print("------------\t----------\t---------------\t------------------\t----")
    print(scheduler.generate_job_report())

    # print header for node data
    print("\n## NODE INFORMATION ##\n")
    print("name\ttotal_compute_time (dd:hh:mm:ss)\ttotal_idle_time (dd:hh:mm:ss)\t" +
            "total_energy_consumption (kWh)\ttotal_energy_cost")
    print("----\t------------------------\t---------------------\t" +
            "------------------------------")
    print(scheduler.generate_node_report())
Ejemplo n.º 29
0
from src.scheduler import Scheduler
from lib import lib
import pandas as pd
import datetime

base_config = lib.load_yaml('base_config')

if __name__ == '__main__':
    medic_directory = pd.read_csv(base_config['medic_directory_file_path'])
    scheduler = Scheduler(medic_directory=medic_directory, timezone='US/Central')
    output_file_name = 'schedule'
    scheduler.run(output_file_path='{}/{}'.format(base_config['output_directory'], output_file_name))
    # test_time = datetime.datetime(2017, 8, 22, 8, 17)
    # now_time = datetime.datetime.utcnow()
    # print(test_time.time(), datetime.time(now_time.month, now_time.hour, now_time.minute))
    # scheduler.alert_medic(medic=None, signup_time=test_time)
Ejemplo n.º 30
0
def test_create_event(capsys):
    Scheduler.create_event('test', '2021-01-30 19:25:00')
    cp = capsys.readouterr()
    assert not cp.err
Ejemplo n.º 31
0
def set_schedule(interval, unit):
    Scheduler.start(interval, unit)
Ejemplo n.º 32
0
from src.dep_controller import DepController
from src.req_handler import ReqHandler
from src.node_controller import NodeController
from src.scheduler import Scheduler
import unittest
import time

_nodeCtlLoop = 2
_depCtlLoop = 2
_scheduleCtlLoop = 2

apiServer = APIServer()
depController = DepController(apiServer, _depCtlLoop)
nodeController = NodeController(apiServer, _nodeCtlLoop)
reqHandler = ReqHandler(apiServer)
scheduler = Scheduler(apiServer, _scheduleCtlLoop)
depControllerThread = threading.Thread(target=depController)
nodeControllerThread = threading.Thread(target=nodeController)
reqHandlerThread = threading.Thread(target=reqHandler)
schedulerThread = threading.Thread(target=scheduler)
print("Threads Starting")
reqHandlerThread.start()
nodeControllerThread.start()
depControllerThread.start()
schedulerThread.start()
print("ReadingFile")

instructions = open("tracefiles/delete_deployment.txt", "r")
commands = instructions.readlines()
for command in commands:
    cmdAttributes = command.split()