Running Server Script Automatically

Hi, there.
Hope you’ll doing great!
I have a doctype called: TheYear. It has just one field named Year
I created one document with value 2021. And wrote a script to automatically check the last document and create new one if the next year comes. Like this:

import frappe
from frappe.model.document import Document
import datetime


class TheYear(Document):

    # Getting current year
    this_year = datetime.datetime.today().year
	
    # Checking for the last updated document date
    if int(frappe.get_last_doc('TheYear').year) != this_year:
        doc = frappe.get_doc({'doctype': 'TheYear', 'year': this_year})
        doc.insert()
        doc.submit()
        frappe.db.commit()

The code works perfectly from bench console
And with no response when created new server script:


I chose Daily just to test

And with Error when wrote the code inside the theyear.py file:

Hope you can help me through this.
Thanks in advance

Import statements and class declarations can not be put in Server Scripts.

What is the solution, then?
From hooks… py?

TheYear doctype should be created as custom DocType first.

Then remove all imports and class declaration, the script will be look like below and will work.

# Getting current year
this_year = YOUR_DATE_HERE

# Checking for the last updated document date
if int(frappe.get_last_doc('TheYear').year) != this_year:
    doc = frappe.get_doc({'doctype': 'TheYear', 'year': this_year})
    doc.insert()
    doc.submit()
    frappe.db.commit()

Thank you.
I did it, but didn’t work.
I figured it out, though :ok_hand:
Using hooks.py