0

I would like to execute a portion of script once daily for about 7 days. I used the datetime module in getting the current date, the timedelta module in calculating the runtime of the program, and the localtime() in specifying a particular time the code is to run daily. The first time I executed it, the balance doesn't add up automically. I think it keeps reassigning the balance variable.

Here is a portion of my code.

balance = 0
percentage = 5
deposit = 0
profit = 0
active = True 

while active:
if current_date < expiring_date:
    balance = deposit + percentage
    current_date = current_date + timedelta(hours=24)
    if time.localtime().tm_hr == 2:
        balance += percentage
else:
    active = False

Then, I modified the code by using conditionals to check if the initial balance is 0, to prevent the reassign ing. Currently the code executes at once, which is not what I want. I want it to run daily, and for each run, it should add the percentage to the current balance till the codition evaluates to False. I also want to keep a track of balance, and return the new balance at the end of each day. Is there a better way of doing it without keeping the loop running for days,and consuming power.

while active:
    if current_date < expiring_date:
        if balance <= 0:
            balance = deposit + percentage
            current_date = current_date + timedelta(hours=24)
        else:
            if time.localtime().tm_hr == 2:
                balance += percentage
                current_date = current_date + timedelta(hours=24)
     else:
         active = False
Buchii
  • 31
  • 6
  • Remove the while loop, and create a crontab (or whatever scheduler in your OS) rule to run your code daily. – Jorge Campos Oct 23 '22 at 04:48
  • Another option is to add a sleep until next day to your code after it run once, if you absolutely want it running – Jorge Campos Oct 23 '22 at 04:50
  • I don't know how to use a crontab. Would you mind showing me an example? Thanks. – Buchii Oct 23 '22 at 05:19
  • Look at this thread https://stackoverflow.com/q/8727935/460557 and to get the right cron expression check it here how to change it: https://crontab.cronhub.io/ – Jorge Campos Oct 23 '22 at 19:16

0 Answers0