全部删除后未删除python cronjob

2024-09-29 00:12:29 发布

您现在位置:Python中文网/ 问答频道 /正文

TLDR:使用python时,crontab.remove\u all似乎可以工作,但是当我实例化一个新的crontab时,我可以看到remove\u all命令不起作用

长问题: 我试图在我的项目中使用cronjobs,但在此之前,我希望能够测试它们。因为我不想有无限多的作业在运行,我需要首先能够删除它们。然而,它并不像我想象的那样工作

这是我的密码:

    def test_understanding_cronjobs(self):
        """
        Just trying to understand cronjobs and how to delete them.
        The main point of this experiment is to have a way to clean everything
        between each test.
        """
        # First we instanciate a crontab object.
        crontab = CronTab(user="root")

        # Then we make sure that there are no other test cronjobs running.
        # I know everything should be clean at the start of a test, but this is to show
        # that my environment is clean.
        crontab.remove_all(comment="test")
        # There should be no job at all now.
        self.assertEqual(len(crontab), 0)

        # We create a single job, with a comment that will allow us to kown that it's a test.
        # https://stackabuse.com/scheduling-jobs-with-python-crontab/
        job = crontab.new(command="ls -al /tmp", comment="test")
        job.minute.every(1)
        crontab.write()

        # At this point we should have one and only one job.
        self.assertEqual(len(crontab), 1)

        # Let's delete all test jobs.
        crontab.remove_all(comment="test")
        # There should be no job at all now.
        self.assertEqual(len(crontab), 0)

        # Just to be sure, let's create a new crontab instance and verify this information.
        clean_crontab = CronTab(user="root")
        self.assertEqual(len(clean_crontab), 0)
        # But here I get : AssertionError: 1 != 0, self.assertEqual(len(clean_crontab), 0)

如果你对那里发生的事情有任何想法,我真的很想听听


Tags: totestselfcleanlenthatjobbe
1条回答
网友
1楼 · 发布于 2024-09-29 00:12:29

crontab只是与系统的cron管理进行交互。如果您不write更改,它们不会被提交,因此实例化一个新的crontab对象将读取现有内容,而不是“挂起”工作

    # Let's delete all test jobs.
    crontab.remove_all(comment="test")
    # There should be no job at all now.
    self.assertEqual(crontab.__len__(), 0)
    # <- changes not saved here
    # Just to be sure, let's create a new crontab instance and verify this information.
    clean_crontab = CronTab(user="root") # <- reads existing stuff from system, only goes up to the previous write

 self.assertEqual(crontab.__len__(), 0)

WTF不应该直接调用dunder方法,除非覆盖它们

相关问题 更多 >