def run(self):
        schedule.every().day.at("14:55").do(self.marketFunc)

        while True:
            schedule.run_pending()
            logging.info('WAIT {} sec'.format(schedule.idle_seconds()))
            time.sleep(max(schedule.idle_seconds(), 1))
Example #2
0
    def run(self):
        schedule.every().day.at("21:00").do(self.tradeFunc)
        schedule.every().day.at("09:00").do(self.tradeFunc)

        while True:
            schedule.run_pending()
            logging.info('WAIT {} sec'.format(schedule.idle_seconds()))
            sleep(max(schedule.idle_seconds(), 1))
Example #3
0
    def test_idle_seconds(self):
        assert schedule.next_run() is None
        assert schedule.idle_seconds() is None

        mock_job = make_mock_job()
        with mock_datetime(2020, 12, 9, 21, 46):
            job = every().hour.do(mock_job)
            assert schedule.idle_seconds() == 60 * 60
            schedule.cancel_job(job)
            assert schedule.next_run() is None
            assert schedule.idle_seconds() is None
Example #4
0
def main(args):

    # function that will be ran repeatedly
    def f():
        filename = copy(args.experiment,
                        src_file=args.filename,
                        verbose=args.no_verbose)

        if args.gifs:
            gif_filename = filename.split('/')[-1].split('.')[0]
            mg.make_gif(filename,
                        os.path.join(args.experiment, 'gifs'),
                        map=args.map,
                        filename=gif_filename,
                        fps=25)

    # scheduling the function to occur at given frequency
    schedule.every(args.frequency).minutes.do(f)

    # performing the function immediately
    f()

    # infinite loop calling the function or printing time until next call
    while True:
        n_seconds = schedule.idle_seconds()

        if n_seconds > 0:
            fmt_time = str(datetime.timedelta(seconds=int(n_seconds)))
            print(f'Time til next copy: {fmt_time}', end='\r')
        else:
            schedule.run_pending()

        time.sleep(1)
def run():
    N.UPDATE_JOBS_INTERVAL.do(schedule_update)
    while True:
        schedule.run_pending()
        if schedule.next_run() is None:
            break
        time.sleep(schedule.idle_seconds())
Example #6
0
def run_scheduled_tasks():
    """Run the scheduled tasks using the 'schedule' package."""

    # always send a device update upon start up (in case the device is new to the server)
    send_device_update()

    try:
        while True:
            idle_seconds = schedule.idle_seconds()

            if idle_seconds is None:
                # no more jobs to run
                LOGGER.warning("No more jobs for scheduler to run")
                break

            if idle_seconds > 0:
                # sleep till the next scheduled job needs to be run
                LOGGER.debug(f"scheduler sleeping for {idle_seconds} seconds.")
                time.sleep(idle_seconds)

            start = time.time()
            schedule.run_pending()
            end = time.time()
            elapsed_time = end - start
            LOGGER.debug(f"SCHEDULER - took: {elapsed_time} seconds to run")
    except KeyboardInterrupt:
        LOGGER.info("Stopping scheduler")

    LOGGER.info("Scheduler is exiting")
Example #7
0
 async def run(self):
     schedule.every().day.at('05:30').do(self.clean_rooms)
     schedule.every().day.at('15:30').do(self.clean_rooms)
     await asyncio.sleep(120)
     while True:
         await asyncio.sleep(schedule.idle_seconds() + 1)
         schedule.run_pending()
Example #8
0
    def run(self):
        # Compute start time
        t = time(hour=0, minute=0)
        soff = timedelta(minutes=self.starttime)
        t = datetime.combine(date.today(), t) + soff

        now = datetime.now()

        soff = t - now
        if soff.total_seconds() < 0:
            # We missed the window.  Wait until the next day.
            soff = soff + timedelta(days=1)

        print "First start is in %s" % soff

        # Wait for first iteration
        sleep(soff.total_seconds())

        job = schedule.every(self.period).minutes.do(self.job)

        # Do the first run
        schedule.run_all()

        while True:
            print "Next run at %s" % job.next_run
            sleep(schedule.idle_seconds() + 1)
            schedule.run_pending()
Example #9
0
 def background_task(self):
     schedule.run_pending()
     # restart with proper interval here
     self.bg_task = threading.Timer(schedule.idle_seconds(),
                                    self.background_task)
     self.bg_task.daemon = True  # thread dies with main
     self.bg_task.start()
Example #10
0
def run_scheduled_refresh(args, config):
    logger = get_logger(__name__)
    reader = StatsReader(config)
    ctx = RefreshContext(reader, args.database)

    def job():
        old_hosts = reader.hosts
        try:
            config = read_config(args.config)
            reader.update_hosts(config)
        except:
            reader.hosts = old_hosts
        ctx.refresh_all()

    if not setup_scheduled_refresh(job, args, config):
        return

    exit_event = config['event'] if 'event' in config else Event()

    if current_thread() is main_thread():
        setup_signal_handlers(exit_event)

    while not exit_event.is_set():
        idle = schedule.idle_seconds()
        if idle > 0:
            exit_event.wait(idle)
            if exit_event.is_set():
                return

        logger.debug('Run refresh')
        schedule.run_pending()
Example #11
0
 def background_task(self):
     schedule.run_pending()
     # restart with proper interval here
     self.bg_task = threading.Timer(schedule.idle_seconds(),
                                    self.background_task)
     self.bg_task.daemon = True  # thread dies with main
     self.bg_task.start()
def get_email(email, ticker):
    # while True:
    #     schedule.every(20).seconds.do(job, email=email)
    #     schedule.run_pending()
    #     time.sleep(1)
    schedule.every(5).seconds.do(job, args_=[email, ticker])
    while 1:
        n = schedule.idle_seconds()
        if n is None:
            break
        elif n > 0:
            time.sleep(0.5)
        schedule.run_pending()


# import schedule
# import time

# def job():
#     print('Hello')

# schedule.every(5).seconds.do(job)

# while 1:
#     n = schedule.idle_seconds()
#     if n is None:
#         # no more jobs
#         break
#     elif n > 0:
#         arr = [5,4,3,2,1]
#         arr.sort()
#         print(arr)
#         time.sleep(n)
#     schedule.run_pending()
Example #13
0
def bgWorker():
    global run_threads
    sleeptime = 2
    while run_threads:
        if sleeptime > 0:
            time.sleep(sleeptime)
        jLog.debug('Running jobs...')
        schedule.run_pending()
        sleeptime = schedule.idle_seconds()
Example #14
0
def run() -> None:
    run_pipeline()  # run once when starting to catch new errors when deploying

    schedule.every().day.at('04:00').do(run_pipeline)

    while True:
        schedule.run_pending()
        wait = schedule.idle_seconds()
        print('Waiting {} seconds until the next run'.format(wait))
        time.sleep(wait)
Example #15
0
 def test_next_run_property(self):
     original_datetime = datetime.datetime
     with mock_datetime(2010, 1, 6, 13, 16):
         hourly_job = make_mock_job('hourly')
         daily_job = make_mock_job('daily')
         every().day.do(daily_job)
         every().hour.do(hourly_job)
         assert len(schedule.jobs) == 2
         # Make sure the hourly job is first
         assert schedule.next_run() == original_datetime(2010, 1, 6, 14, 16)
         assert schedule.idle_seconds() == 60 * 60
Example #16
0
 def test_next_run_property(self):
     original_datetime = datetime.datetime
     with mock_datetime(2010, 1, 6, 13, 16):
         hourly_job = make_mock_job('hourly')
         daily_job = make_mock_job('daily')
         every().day.do(daily_job)
         every().hour.do(hourly_job)
         assert len(schedule.jobs) == 2
         # Make sure the hourly job is first
         assert schedule.next_run() == original_datetime(2010, 1, 6, 14, 16)
         assert schedule.idle_seconds() == 60 * 60
Example #17
0
def main():
    for t in range(24):
        d = f'{t:02d}:5'
        schedule.every().day.at(d).do(job)

    while True:
        schedule.run_pending()
        til_next = int(schedule.idle_seconds()/60)
        if til_next % 10 == 0:
            print(f'Next Task running in: {til_next} minutes')
        sleep(1)
Example #18
0
class Zeitplan:
    schedule.every(5).seconds.do(rssFetch)

    while 1:
        n = schedule.idle_seconds()
        if n is None:
            # no more jobs
            break
        elif n > 0:
            # sleep exactly the right amount of time
            time.sleep(n)
        schedule.run_pending()
Example #19
0
def main():
    if not azan_time.exists():
        logger.info('File "azan-time.txt" not exists.')
        update_time()
    schedule.every(3).seconds.do(create_job_once)
    schedule.every().day.at('00:05').do(update_time)
    schedule.every().day.at('00:10').do(create_job)
    logger.info('Running service in background...')
    while True:
        n = schedule.idle_seconds()
        logger.info(f'Next job in {round(n/60, 2)} minutes...')
        if n is None: break
        elif n > 0: time.sleep(n)
        schedule.run_pending()
Example #20
0
def __schedule_loop():
    while True:
        log.debug("Running pending scheduled tasks.")
        schedule.run_pending()

        sleep_time = SCHEDULING_SLEEP_INTERVAL
        if schedule.next_run() is not None:
            sleep_time = schedule.idle_seconds()

        if sleep_time < 0:
            sleep_time = SCHEDULING_SLEEP_INTERVAL

        log.debug("Scheduling thread sleeping for: '{}' seconds".format(sleep_time))
        time.sleep(sleep_time)
Example #21
0
def main():
    bot = Bot(os.path.join(path, "vacancies.bot"))
    bot.dp.add_handler(CommandHandler("run", lambda dummy, update: run_cmd(bot, update)))
    
    schedule.every().day.at("08:00").do(loop_files, bot)
    schedule.every().day.at("18:00").do(loop_files, bot)
        
    while True:
        try:
            time.sleep(schedule.idle_seconds())
            schedule.run_pending()
        except (KeyboardInterrupt, SystemExit):
            os._exit(1)
        except:
            logging.exception(f"{Storage.make_timestamp()}: An error occured", exc_info=True)
Example #22
0
def _schedule_once(exit_handler: ExitHandler) -> float:
    try:
        log.debug("Running pending scheduled tasks.")
        schedule.run_pending()

        sleep_time = SCHEDULING_SLEEP_INTERVAL
        if schedule.next_run() is not None:
            sleep_time = schedule.idle_seconds()

        if sleep_time < 0:
            sleep_time = SCHEDULING_SLEEP_INTERVAL

        return sleep_time
    except Exception:
        log.error("Failed to run scheduling once")
        exit_handler.exit(SCHEDULE_ONCE_FAILURE_EXIT_CODE)
Example #23
0
def main():
    """The main program"""

    for show in read_shows("./config.yml"):
        schedule_show(show)

    while True:
        sleep_time = idle_seconds()

        if sleep_time and sleep_time > 0:
            info(f"Sleeping {sleep_time} seconds until next schedule")
            sleep(sleep_time)
            run_pending()
        else:
            info("Nothing is scheduled, so exiting")
            return
Example #24
0
async def add_onlinerooms_monitor():
    monitors: List[DanmuRaffleMonitor] = []
    schedule.every().day.at('05:00').do(clean_rooms, monitors)
    schedule.every().day.at('15:00').do(clean_rooms, monitors)
    area_id = 0
    while True:
        if schedule.idle_seconds() <= 3:
            await asyncio.sleep(5)
            schedule.run_pending()
            await asyncio.sleep(120)

        list_new_rooms = await refresh_online_roomid()

        set_new_rooms = set(list_new_rooms)
        set_common_rooms = set()
        list_unique_old_index = []  # 过期(下线)的直播间
        for i, monitor in enumerate(monitors):
            room_id = monitor.room_id
            if not monitor.paused and room_id and room_id in set_new_rooms:
                set_common_rooms.add(room_id)
            elif monitor.paused:
                list_unique_old_index.append(i)

        set_unique_new_rooms = set_new_rooms - set_common_rooms

        print('监控重启的数目', len(set_unique_new_rooms), len(list_unique_old_index))

        for monitor_index, new_roomid in zip_longest(list_unique_old_index,
                                                     set_unique_new_rooms):
            if monitor_index is not None:
                monitor = monitors[monitor_index]
                if new_roomid is None:
                    pass  # list_unique_old_index 肯定都是pause的了
                else:
                    await monitor.reset_roomid(new_roomid)
                    monitor.resume()
            else:  # 新房间很多,老房间不够用,需要扩充
                # list_unique_old_index先到了头,那么set_unique_new_rooms一定还有多余,一定非 None
                monitor = DanmuRaffleMonitor(new_roomid, area_id)
                loop.create_task(monitor.run())
                if not area_id % 20:
                    await asyncio.sleep(0.2)
                area_id += 1
                monitors.append(monitor)
        bili_statistics.max_room_num(area_id)
        if set_unique_new_rooms:
            await asyncio.sleep(7)
Example #25
0
def run(add_delay=2.5, sort='votes', no_search=False, run_now=False, no_notifications=False, ignore_blacklist=False):
    log.info("Automatic mode is now running...")

    # Add tasks to schedule and do first run if enabled
    if cfg.automatic.movies.interval:
        movie_schedule = schedule.every(cfg.automatic.movies.interval).hours.do(
            automatic_movies,
            add_delay,
            sort,
            no_search,
            not no_notifications,
            ignore_blacklist,
            int(cfg.filters.movies.rating_limit) if cfg.filters.movies.rating_limit != "" else None
        )
        if run_now:
            movie_schedule.run()

            # Sleep between tasks
            time.sleep(add_delay)

    if cfg.automatic.shows.interval:
        shows_schedule = schedule.every(cfg.automatic.shows.interval).hours.do(
            automatic_shows,
            add_delay,
            sort,
            no_search,
            not no_notifications,
            ignore_blacklist
        )
        if run_now:
            shows_schedule.run()

            # Sleep between tasks
            time.sleep(add_delay)

    # Enter running schedule
    while True:
        try:
            # Sleep until next run
            log.info("Next job at %s", schedule.next_run())
            time.sleep(max(schedule.idle_seconds(), 0))
            # Check jobs to run
            schedule.run_pending()

        except Exception as e:
            log.exception("Unhandled exception occurred while processing scheduled tasks: %s", e)
            time.sleep(1)
Example #26
0
    def _run(self):
        while True:
            _schedule.run_pending()

            nextsched = self.sched.run(False)
            if nextsched is None:
                nextsched = Inf

            try:
                nextschedule = _schedule.idle_seconds()
            except Exception:
                nextschedule = Inf

            if nextsched == nextschedule == Inf:
                self._delay(1)  # Finish init
            else:
                self._delay(min(nextsched, nextschedule))
Example #27
0
    def __init__(self):
        """ This creates a new queue executor.

        This creates a new Executor object; it does not start the executor, or load
        the queue from the database.
        """

        # initialize logging system
        if not Executor.log:
            Executor.__init_log()

        # say hi
        self.log.info('Executor is starting up...')

        # dummy telescope variable
        self.telescope: telescope.Telescope = None

        # create connection to database; this raises a fatal
        # exception if it fails
        self.db = database.Database()

        # create calendar
        self.log.info('Connecting to Google Calendar...')
        self.calendar = calendar.Calendar()

        # variable to store completed observations every night
        self.completed_observations = []

        # schedule the start function to run each night at the
        # designated start time (in the servers timezone)
        run.every().day.at(config.queue.start_time).do(self.start)

        # the execution loop; this waits until the appropriate time
        # and then runs self.start()
        while True:

            # we try and start the queue
            self.start()

            # otherwise wait until we are meant to start at night
            self.log.info(f'Executor is initialized and waiting {run.idle_seconds()/60/60:.1f} hours to the designated start time...')
            time.sleep(int((1/24)*run.idle_seconds())) # check in roughly every hour

            self.log.info('Executor is awake; checking if any jobs need to be run...')
            run.run_pending()
Example #28
0
def run() -> None:
    """Loop eternally and run schedulers at configured times."""
    for s in ALL_SCHEDULERS:
        job = getattr(schedule.every(s.period), s.time_unit)
        if s.at:
            job = job.at(s.at)
        job.do(s).tag(s.name)
    log.info("Starting Schedule")
    for j in schedule.jobs:
        log.info("%s: %s", ", ".join(j.tags), j)
    while True:
        schedule.run_pending()
        idle = schedule.idle_seconds()
        if idle < 0:
            log.info("Next job in queue is scheduled in the past, run it now.")
        else:
            log.info("Sleeping for %d seconds", idle)
            sleep(idle)
Example #29
0
    def run(self):
        # pip install schedule
        import schedule
        schedule.every().day.at("11:00").do(
            lambda: self.about_show_message.emit("Пора в столовку"))
        schedule.every().day.at("13:00").do(
            lambda: self.about_show_message.emit("Иди прогуляйся"))
        schedule.every().day.at("15:00").do(
            lambda: self.about_show_message.emit("Иди прогуляйся"))
        schedule.every().day.at("17:00").do(
            lambda: self.about_show_message.emit("Иди прогуляйся"))
        schedule.every().day.at("19:00").do(
            lambda: self.about_show_message.emit("Вали домой"))

        description = 'Jobs:\n'
        description_gui = ''
        for job in schedule.jobs:
            description += '    ' + str(job) + "\n"
            description_gui += str(job) + "\n"

        # Костыль для показа сообщения вида "Every 1 day at 11:00:00"
        import re
        pattern = re.compile(
            r' do <lambda>\(\) \(last run: .+?, next run: .+?\)')
        description = pattern.sub('', description)
        description_gui = pattern.sub('', description_gui)

        print(description)

        while True:
            schedule.run_pending()

            import time
            time.sleep(1)

            next_job_time = schedule.next_run().time()
            idle_secs = int(schedule.idle_seconds())

            local_description_gui = description_gui
            local_description_gui += '\n\n'
            local_description_gui += 'Следующий перерыв будет в {}, осталось {} секунд'.format(
                next_job_time, idle_secs)
            self.about_description.emit(local_description_gui)
Example #30
0
def cmd_run(options):
    logging.info('Starting scheduler')

    schedule.every().day.at(options.at).do(backup_all)

    last_next_run = None

    while True:

        next_run = schedule.next_run()
        if next_run != last_next_run:
            last_next_run = next_run
            next_run_str = schedule.next_run().strftime("%c")
            next_run_seconds = schedule.idle_seconds()
            logging.info('Next run is at ' + next_run_str + ' that is still ' +
                         str(next_run_seconds) + ' seconds')

        schedule.run_pending()
        time.sleep(1)
Example #31
0
    def _schedule_in_main_thread(self):
        """
        Run scheduler in the main thread.
        If ``run_continuous`` is true then it will continuously run the jobs on schedule.
        Otherwise run all jobs at once.

        """

        if self._run_continuous:
            audit_params(Sc.OPERATION_START_JOBS, Sc.STATUS_STARTED,
                         Sc.MSG_JOB_STARTED.format(str(self._print_etr)))
            self._started = True
            while True:
                try:
                    if not self._run_continuous:
                        print(Sc.MSG_SHUTDOWN_SCHEDULER_RUNNING_ALL)
                        schedule.run_all()
                        self.__wait = False
                        self._shutdown_requested = False
                        self._started = False
                        break

                    self._next_run = schedule.next_run()
                    self._idle_seconds = schedule.idle_seconds()
                    self._log_etr()

                    schedule.run_pending()

                    time.sleep(self._pulse)
                except KeyboardInterrupt:
                    audit_params(operation=Sc.OPERATION_SHUTDOWN,
                                 status=Sc.STATUS_INTERRUPTED,
                                 comments=Sc.MSG_SCHEDULER_INTERRUPTED)
                    schedule.run_all()
                    self.__wait = False
                    self._shutdown_requested = False
                    self._started = False
                    break
        else:
            audit_params(Sc.OPERATION_START_JOBS, Sc.STATUS_STARTED,
                         Sc.MSG_JOB_STARTED.format(str(self._print_etr)))
            schedule.run_all()
Example #32
0
def main():
    bot = Bot(os.path.join(path, "binck.bot"))
    bot.dp.add_handler(CommandHandler("check", lambda dummy1, resp: check(resp, bot)))
    bot.dp.add_handler(CommandHandler("cash", lambda dummy1, resp, args: cash(resp, bot, args[0]), pass_args=True))
    
    schedule.every().monday.at("17:00").do(update, bot)
    schedule.every().tuesday.at("17:00").do(update, bot)
    schedule.every().wednesday.at("17:00").do(update, bot)
    schedule.every().thursday.at("17:00").do(update, bot)
    schedule.every().friday.at("17:00").do(update, bot)
    
    while True:
        try:
            time.sleep(schedule.idle_seconds())
            schedule.run_pending()
        except (KeyboardInterrupt, SystemExit):
            os._exit(1)
        except:
            raise
            logging.exception(f"{Storage.make_timestamp()}: An error occured", exc_info=True)
Example #33
0
    def test_next_run_property(self):
        class MockDate(datetime.datetime):
            @classmethod
            def today(cls):
                return cls(2010, 1, 6)

            @classmethod
            def now(cls):
                return cls(2010, 1, 6, 13, 16)
        original_datetime = datetime.datetime
        datetime.datetime = MockDate

        hourly_job = make_mock_job('hourly')
        daily_job = make_mock_job('daily')
        every().day.do(daily_job)
        every().hour.do(hourly_job)
        assert len(schedule.jobs) == 2
        # Make sure the hourly job is first
        assert schedule.next_run() == original_datetime(2010, 1, 6, 14, 16)
        assert schedule.idle_seconds() == 60 * 60

        datetime.datetime = original_datetime