Skip to main content

์ž‘์—… ์Šค์ผ€์ค„๋ง

Python์œผ๋กœ ์ •๊ธฐ์ ์ธ ์ž‘์—…์„ ์ž๋™์œผ๋กœ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ผ์ผ ๋ฐฑ์—…, ์ •๊ธฐ ๋ฆฌํฌํŠธ, ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ๋“ฑ์„ ์Šค์ผ€์ค„๋งํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

schedule ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌโ€‹

์„ค์น˜ํ•˜๊ธฐโ€‹

pip install schedule

๊ธฐ๋ณธ ์‚ฌ์šฉ๋ฒ•โ€‹

import schedule
import time

def job():
print("์ž‘์—… ์‹คํ–‰!")

# 10์ดˆ๋งˆ๋‹ค ์‹คํ–‰
schedule.every(10).seconds.do(job)

# 10๋ถ„๋งˆ๋‹ค ์‹คํ–‰
schedule.every(10).minutes.do(job)

# 1์‹œ๊ฐ„๋งˆ๋‹ค ์‹คํ–‰
schedule.every().hour.do(job)

# ๋งค์ผ ์‹คํ–‰
schedule.every().day.do(job)

# ๋งค์ฃผ ์›”์š”์ผ ์‹คํ–‰
schedule.every().monday.do(job)

# ๋งค์ฃผ ์ˆ˜์š”์ผ 13:15์— ์‹คํ–‰
schedule.every().wednesday.at("13:15").do(job)

# ๋งค์ผ 10:30์— ์‹คํ–‰
schedule.every().day.at("10:30").do(job)

# ์Šค์ผ€์ค„ ์‹คํ–‰
while True:
schedule.run_pending()
time.sleep(1)

๋‹ค์–‘ํ•œ ์Šค์ผ€์ค„ ํŒจํ„ดโ€‹

์‹œ๊ฐ„ ๊ธฐ๋ฐ˜ ์Šค์ผ€์ค„โ€‹

import schedule

def morning_routine():
print("์ข‹์€ ์•„์นจ์ž…๋‹ˆ๋‹ค!")

def lunch_reminder():
print("์ ์‹ฌ ์‹œ๊ฐ„์ž…๋‹ˆ๋‹ค!")

def evening_report():
print("์ผ์ผ ๋ณด๊ณ ์„œ ์ƒ์„ฑ ์ค‘...")

# ๋งค์ผ ์˜ค์ „ 8์‹œ
schedule.every().day.at("08:00").do(morning_routine)

# ๋งค์ผ ์ •์˜ค
schedule.every().day.at("12:00").do(lunch_reminder)

# ๋งค์ผ ์˜คํ›„ 6์‹œ
schedule.every().day.at("18:00").do(evening_report)

# ํ‰์ผ ์˜ค์ „ 9์‹œ
schedule.every().monday.at("09:00").do(morning_routine)
schedule.every().tuesday.at("09:00").do(morning_routine)
schedule.every().wednesday.at("09:00").do(morning_routine)
schedule.every().thursday.at("09:00").do(morning_routine)
schedule.every().friday.at("09:00").do(morning_routine)

๊ฐ„๊ฒฉ ๊ธฐ๋ฐ˜ ์Šค์ผ€์ค„โ€‹

import schedule

def check_server():
print("์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ")

def collect_data():
print("๋ฐ์ดํ„ฐ ์ˆ˜์ง‘")

# 5๋ถ„๋งˆ๋‹ค
schedule.every(5).minutes.do(check_server)

# 30๋ถ„๋งˆ๋‹ค
schedule.every(30).minutes.do(collect_data)

# 2์‹œ๊ฐ„๋งˆ๋‹ค
schedule.every(2).hours.do(check_server)

# 3์ผ๋งˆ๋‹ค
schedule.every(3).days.do(collect_data)

๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์žˆ๋Š” ์ž‘์—…โ€‹

import schedule

def greet(name):
print(f"์•ˆ๋…•ํ•˜์„ธ์š”, {name}๋‹˜!")

def send_report(email, report_type):
print(f"{email}๋กœ {report_type} ๋ฆฌํฌํŠธ ๋ฐœ์†ก")

# ๋งค๊ฐœ๋ณ€์ˆ˜์™€ ํ•จ๊ป˜ ์‹คํ–‰
schedule.every().day.at("09:00").do(greet, name="ํ™๊ธธ๋™")
schedule.every().day.at("18:00").do(send_report,
email="admin@example.com",
report_type="์ผ์ผ")

์ž‘์—… ์ทจ์†Œโ€‹

import schedule

def some_task():
print("์ž‘์—… ์‹คํ–‰")
# ์กฐ๊ฑด์ด ๋งŒ์กฑ๋˜๋ฉด ์ž‘์—… ์ทจ์†Œ
return schedule.CancelJob

# ์ž‘์—… ๋“ฑ๋ก
job = schedule.every().day.do(some_task)

# ๋‚˜์ค‘์— ์ˆ˜๋™์œผ๋กœ ์ทจ์†Œ
schedule.cancel_job(job)

# ๋ชจ๋“  ์ž‘์—… ์ทจ์†Œ
schedule.clear()

# ํŠน์ • ํƒœ๊ทธ์˜ ์ž‘์—…๋งŒ ์ทจ์†Œ
schedule.clear('daily-tasks')

ํƒœ๊ทธ ์‚ฌ์šฉํ•˜๊ธฐโ€‹

import schedule

def backup():
print("๋ฐฑ์—… ์‹คํ–‰")

def report():
print("๋ฆฌํฌํŠธ ์ƒ์„ฑ")

# ํƒœ๊ทธ ์ง€์ •
schedule.every().day.at("02:00").do(backup).tag('backup', 'critical')
schedule.every().day.at("09:00").do(report).tag('report', 'daily')

# ํŠน์ • ํƒœ๊ทธ์˜ ์ž‘์—…๋งŒ ์‹คํ–‰
schedule.run_all(delay_seconds=0) # ๋ชจ๋“  ์ž‘์—… ์ฆ‰์‹œ ์‹คํ–‰
schedule.run_all('backup') # 'backup' ํƒœ๊ทธ ์ž‘์—…๋งŒ ์‹คํ–‰

# ํŠน์ • ํƒœ๊ทธ์˜ ์ž‘์—… ์ทจ์†Œ
schedule.clear('daily')

์‹ค์ „ ์˜ˆ์ œโ€‹

1. ์ผ์ผ ๋ฐฑ์—… ์ž๋™ํ™”โ€‹

import schedule
import time
import shutil
import os
from datetime import datetime
import zipfile

def create_backup():
"""๋งค์ผ ์ž๋™ ๋ฐฑ์—…"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ๋ฐฑ์—… ์‹œ์ž‘...")

# ๋ฐฑ์—… ๋Œ€์ƒ ํด๋”
source_dirs = [
'/Users/username/Documents',
'/Users/username/Projects'
]

# ๋ฐฑ์—… ์ €์žฅ ์œ„์น˜
backup_dir = '/Users/username/Backups'
os.makedirs(backup_dir, exist_ok=True)

# ๋ฐฑ์—… ํŒŒ์ผ๋ช… (๋‚ ์งœ ํฌํ•จ)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_file = os.path.join(backup_dir, f'backup_{timestamp}.zip')

try:
# ZIP ํŒŒ์ผ ์ƒ์„ฑ
with zipfile.ZipFile(backup_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
for source_dir in source_dirs:
if not os.path.exists(source_dir):
print(f"๊ฒฝ๊ณ : {source_dir} ํด๋”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")
continue

print(f"๋ฐฑ์—… ์ค‘: {source_dir}")

for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, os.path.dirname(source_dir))
zipf.write(file_path, arcname)

# ๋ฐฑ์—… ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
size_mb = os.path.getsize(backup_file) / (1024 * 1024)
print(f"๋ฐฑ์—… ์™„๋ฃŒ: {backup_file} ({size_mb:.2f} MB)")

# ์˜ค๋ž˜๋œ ๋ฐฑ์—… ์ •๋ฆฌ (30์ผ ์ด์ƒ ๋œ ํŒŒ์ผ ์‚ญ์ œ)
cleanup_old_backups(backup_dir, days=30)

except Exception as e:
print(f"๋ฐฑ์—… ์‹คํŒจ: {e}")

def cleanup_old_backups(backup_dir, days=30):
"""์˜ค๋ž˜๋œ ๋ฐฑ์—… ํŒŒ์ผ ์‚ญ์ œ"""

now = time.time()
cutoff = now - (days * 86400) # days๋ฅผ ์ดˆ๋กœ ๋ณ€ํ™˜

for filename in os.listdir(backup_dir):
if filename.startswith('backup_') and filename.endswith('.zip'):
file_path = os.path.join(backup_dir, filename)
file_time = os.path.getmtime(file_path)

if file_time < cutoff:
os.remove(file_path)
print(f"์‚ญ์ œ: {filename} (์ƒ์„ฑ ํ›„ {days}์ผ ๊ฒฝ๊ณผ)")

# ๋งค์ผ ์ƒˆ๋ฒฝ 2์‹œ์— ๋ฐฑ์—… ์‹คํ–‰
schedule.every().day.at("02:00").do(create_backup)

print("๋ฐฑ์—… ์Šค์ผ€์ค„๋Ÿฌ ์‹œ์ž‘")
print("๋งค์ผ 02:00์— ๋ฐฑ์—…์ด ์‹คํ–‰๋ฉ๋‹ˆ๋‹ค.")

# ํ…Œ์ŠคํŠธ๋ฅผ ์œ„ํ•ด ์ฆ‰์‹œ ์‹คํ–‰
# create_backup()

while True:
schedule.run_pending()
time.sleep(60) # 1๋ถ„๋งˆ๋‹ค ์ฒดํฌ

2. ์ด๋ฉ”์ผ ๋ฆฌํฌํŠธ ์ž๋™ ๋ฐœ์†กโ€‹

import schedule
import time
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os

def send_daily_report():
"""์ผ์ผ ๋ฆฌํฌํŠธ ์ด๋ฉ”์ผ ๋ฐœ์†ก"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ๋ฆฌํฌํŠธ ์ƒ์„ฑ ์ค‘...")

# ๋ฆฌํฌํŠธ ๋ฐ์ดํ„ฐ ์ƒ์„ฑ (์˜ˆ์‹œ)
report_data = generate_report()

# ์ด๋ฉ”์ผ ์„ค์ •
sender_email = "your_email@gmail.com"
sender_password = "your_app_password"
recipient_email = "recipient@example.com"

# ์ด๋ฉ”์ผ ๋ฉ”์‹œ์ง€ ์ƒ์„ฑ
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = f"์ผ์ผ ๋ฆฌํฌํŠธ - {datetime.now().strftime('%Y-%m-%d')}"

# ์ด๋ฉ”์ผ ๋ณธ๋ฌธ
body = f"""
<html>
<body>
<h2>์ผ์ผ ๋ฆฌํฌํŠธ</h2>
<p>๋‚ ์งœ: {datetime.now().strftime('%Y๋…„ %m์›” %d์ผ')}</p>

<h3>์ฃผ์š” ์ง€ํ‘œ</h3>
<ul>
<li>์ด ๋ฐฉ๋ฌธ์ž: {report_data['visitors']:,}๋ช…</li>
<li>์‹ ๊ทœ ๊ฐ€์ž…: {report_data['signups']:,}๋ช…</li>
<li>๋งค์ถœ: {report_data['revenue']:,}์›</li>
</ul>

<p>์ƒ์„ธ ๋‚ด์šฉ์€ ์ฒจ๋ถ€ ํŒŒ์ผ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”.</p>
</body>
</html>
"""

message.attach(MIMEText(body, 'html'))

# ํŒŒ์ผ ์ฒจ๋ถ€ (์„ ํƒ์‚ฌํ•ญ)
report_file = 'daily_report.csv'
if os.path.exists(report_file):
with open(report_file, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={report_file}')
message.attach(part)

try:
# SMTP ์„œ๋ฒ„ ์—ฐ๊ฒฐ ๋ฐ ์ „์†ก
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login(sender_email, sender_password)
server.send_message(message)

print("๋ฆฌํฌํŠธ ๋ฐœ์†ก ์™„๋ฃŒ!")

except Exception as e:
print(f"์ด๋ฉ”์ผ ๋ฐœ์†ก ์‹คํŒจ: {e}")

def generate_report():
"""๋ฆฌํฌํŠธ ๋ฐ์ดํ„ฐ ์ƒ์„ฑ (์˜ˆ์‹œ)"""
# ์‹ค์ œ๋กœ๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊ฐ€์ ธ์˜ด
return {
'visitors': 1234,
'signups': 56,
'revenue': 5678900
}

# ๋งค์ผ ์˜ค์ „ 9์‹œ์— ๋ฆฌํฌํŠธ ๋ฐœ์†ก
schedule.every().day.at("09:00").do(send_daily_report)

# ๋งค์ฃผ ์›”์š”์ผ ์˜ค์ „ 10์‹œ์— ์ฃผ๊ฐ„ ๋ฆฌํฌํŠธ
def send_weekly_report():
print("์ฃผ๊ฐ„ ๋ฆฌํฌํŠธ ๋ฐœ์†ก")
# ์ฃผ๊ฐ„ ๋ฆฌํฌํŠธ ๋กœ์ง

schedule.every().monday.at("10:00").do(send_weekly_report)

print("๋ฆฌํฌํŠธ ์Šค์ผ€์ค„๋Ÿฌ ์‹œ์ž‘")
print("- ๋งค์ผ 09:00: ์ผ์ผ ๋ฆฌํฌํŠธ")
print("- ๋งค์ฃผ ์›”์š”์ผ 10:00: ์ฃผ๊ฐ„ ๋ฆฌํฌํŠธ")

while True:
schedule.run_pending()
time.sleep(60)

3. ์›น ๋ฐ์ดํ„ฐ ์ •๊ธฐ ์ˆ˜์ง‘โ€‹

import schedule
import time
from datetime import datetime
import requests
from bs4 import BeautifulSoup
import csv
import os

def collect_stock_prices():
"""์ฃผ์‹ ๊ฐ€๊ฒฉ ์ •๊ธฐ ์ˆ˜์ง‘"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์‹œ์ž‘...")

stocks = ['AAPL', 'GOOGL', 'MSFT', 'AMZN']
data = []

for stock in stocks:
try:
# API ๋˜๋Š” ์›น ์Šคํฌ๋ž˜ํ•‘์œผ๋กœ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
# ์—ฌ๊ธฐ์„œ๋Š” ์˜ˆ์‹œ๋กœ ๋žœ๋ค ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ
import random
price = random.uniform(100, 500)

data.append({
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'stock': stock,
'price': round(price, 2)
})

print(f"{stock}: ${price:.2f}")

except Exception as e:
print(f"{stock} ์ˆ˜์ง‘ ์‹คํŒจ: {e}")

# CSV ํŒŒ์ผ์— ์ €์žฅ
save_to_csv(data)

def save_to_csv(data):
"""๋ฐ์ดํ„ฐ๋ฅผ CSV ํŒŒ์ผ์— ์ถ”๊ฐ€"""

filename = f"stock_prices_{datetime.now().strftime('%Y%m')}.csv"
file_exists = os.path.exists(filename)

with open(filename, 'a', newline='', encoding='utf-8') as f:
fieldnames = ['timestamp', 'stock', 'price']
writer = csv.DictWriter(f, fieldnames=fieldnames)

# ํŒŒ์ผ์ด ์—†์œผ๋ฉด ํ—ค๋” ์ถ”๊ฐ€
if not file_exists:
writer.writeheader()

writer.writerows(data)

print(f"๋ฐ์ดํ„ฐ ์ €์žฅ ์™„๋ฃŒ: {filename}")

def analyze_daily_data():
"""ํ•˜๋ฃจ ์ˆ˜์ง‘ํ•œ ๋ฐ์ดํ„ฐ ๋ถ„์„"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ์ผ์ผ ๋ถ„์„ ์ค‘...")

filename = f"stock_prices_{datetime.now().strftime('%Y%m')}.csv"

if not os.path.exists(filename):
print("๋ถ„์„ํ•  ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")
return

# ๋ฐ์ดํ„ฐ ์ฝ๊ธฐ ๋ฐ ๋ถ„์„
stocks_data = {}

with open(filename, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)

for row in reader:
# ์˜ค๋Š˜ ๋‚ ์งœ ๋ฐ์ดํ„ฐ๋งŒ ํ•„ํ„ฐ๋ง
if row['timestamp'].startswith(datetime.now().strftime('%Y-%m-%d')):
stock = row['stock']
price = float(row['price'])

if stock not in stocks_data:
stocks_data[stock] = []

stocks_data[stock].append(price)

# ํ†ต๊ณ„ ์ถœ๋ ฅ
print("\n์ผ์ผ ์ฃผ๊ฐ€ ํ†ต๊ณ„:")
for stock, prices in stocks_data.items():
if prices:
avg = sum(prices) / len(prices)
min_price = min(prices)
max_price = max(prices)

print(f"{stock}:")
print(f" ํ‰๊ท : ${avg:.2f}")
print(f" ์ตœ์ €: ${min_price:.2f}")
print(f" ์ตœ๊ณ : ${max_price:.2f}")
print(f" ๋ณ€๋™: ${max_price - min_price:.2f}")

# ๋งค 30๋ถ„๋งˆ๋‹ค ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
schedule.every(30).minutes.do(collect_stock_prices)

# ๋งค์ผ ์˜คํ›„ 6์‹œ์— ์ผ์ผ ๋ถ„์„
schedule.every().day.at("18:00").do(analyze_daily_data)

print("๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์Šค์ผ€์ค„๋Ÿฌ ์‹œ์ž‘")
print("- 30๋ถ„๋งˆ๋‹ค: ์ฃผ๊ฐ€ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘")
print("- ๋งค์ผ 18:00: ์ผ์ผ ๋ถ„์„")

# ์ฆ‰์‹œ ํ•œ ๋ฒˆ ์‹คํ–‰
collect_stock_prices()

while True:
schedule.run_pending()
time.sleep(60)

4. ์‹œ์Šคํ…œ ๋ชจ๋‹ˆํ„ฐ๋งโ€‹

import schedule
import time
from datetime import datetime
import psutil
import platform

def monitor_system():
"""์‹œ์Šคํ…œ ๋ฆฌ์†Œ์Šค ๋ชจ๋‹ˆํ„ฐ๋ง"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ์‹œ์Šคํ…œ ๋ชจ๋‹ˆํ„ฐ๋ง")

# CPU ์‚ฌ์šฉ๋ฅ 
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU ์‚ฌ์šฉ๋ฅ : {cpu_percent}%")

# ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋ฅ 
memory = psutil.virtual_memory()
print(f"๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋ฅ : {memory.percent}%")
print(f"์‚ฌ์šฉ ์ค‘: {memory.used / (1024**3):.2f} GB / {memory.total / (1024**3):.2f} GB")

# ๋””์Šคํฌ ์‚ฌ์šฉ๋ฅ 
disk = psutil.disk_usage('/')
print(f"๋””์Šคํฌ ์‚ฌ์šฉ๋ฅ : {disk.percent}%")
print(f"๋‚จ์€ ๊ณต๊ฐ„: {disk.free / (1024**3):.2f} GB")

# ๊ฒฝ๊ณ  ์ฒดํฌ
alerts = []

if cpu_percent > 80:
alerts.append(f"โš ๏ธ CPU ์‚ฌ์šฉ๋ฅ  ๋†’์Œ: {cpu_percent}%")

if memory.percent > 80:
alerts.append(f"โš ๏ธ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋ฅ  ๋†’์Œ: {memory.percent}%")

if disk.percent > 90:
alerts.append(f"โš ๏ธ ๋””์Šคํฌ ๊ณต๊ฐ„ ๋ถ€์กฑ: {disk.percent}%")

# ๊ฒฝ๊ณ  ์ถœ๋ ฅ
if alerts:
print("\n๊ฒฝ๊ณ :")
for alert in alerts:
print(alert)

# ์•Œ๋ฆผ ์ „์†ก (์ด๋ฉ”์ผ, ๋ฉ”์‹œ์ง€ ๋“ฑ)
send_alert(alerts)
else:
print("โœ“ ๋ชจ๋“  ์‹œ์Šคํ…œ ์ •์ƒ")

def send_alert(alerts):
"""๊ฒฝ๊ณ  ์•Œ๋ฆผ ์ „์†ก"""
# ์‹ค์ œ๋กœ๋Š” ์ด๋ฉ”์ผ, Slack, SMS ๋“ฑ์œผ๋กœ ์•Œ๋ฆผ
print("\n์•Œ๋ฆผ ์ „์†ก๋จ:")
for alert in alerts:
print(f" {alert}")

def daily_system_report():
"""์ผ์ผ ์‹œ์Šคํ…œ ๋ณด๊ณ ์„œ"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ์ผ์ผ ์‹œ์Šคํ…œ ๋ณด๊ณ ์„œ")

# ์‹œ์Šคํ…œ ์ •๋ณด
print(f"\n์‹œ์Šคํ…œ ์ •๋ณด:")
print(f"OS: {platform.system()} {platform.release()}")
print(f"ํ”„๋กœ์„ธ์„œ: {platform.processor()}")

# ๋ถ€ํŒ… ์‹œ๊ฐ„
boot_time = datetime.fromtimestamp(psutil.boot_time())
print(f"๋ถ€ํŒ… ์‹œ๊ฐ„: {boot_time.strftime('%Y-%m-%d %H:%M:%S')}")

uptime = datetime.now() - boot_time
print(f"๊ฐ€๋™ ์‹œ๊ฐ„: {uptime.days}์ผ {uptime.seconds // 3600}์‹œ๊ฐ„")

# ํ”„๋กœ์„ธ์Šค ์ •๋ณด
print(f"\n์‹คํ–‰ ์ค‘์ธ ํ”„๋กœ์„ธ์Šค: {len(psutil.pids())}๊ฐœ")

# ๋„คํŠธ์›Œํฌ ์ •๋ณด
net_io = psutil.net_io_counters()
print(f"\n๋„คํŠธ์›Œํฌ:")
print(f"์†ก์‹ : {net_io.bytes_sent / (1024**3):.2f} GB")
print(f"์ˆ˜์‹ : {net_io.bytes_recv / (1024**3):.2f} GB")

# 5๋ถ„๋งˆ๋‹ค ์‹œ์Šคํ…œ ๋ชจ๋‹ˆํ„ฐ๋ง
schedule.every(5).minutes.do(monitor_system)

# ๋งค์ผ ์˜ค์ „ 9์‹œ์— ์ผ์ผ ๋ณด๊ณ ์„œ
schedule.every().day.at("09:00").do(daily_system_report)

print("์‹œ์Šคํ…œ ๋ชจ๋‹ˆํ„ฐ๋ง ์‹œ์ž‘")
print("- 5๋ถ„๋งˆ๋‹ค: ๋ฆฌ์†Œ์Šค ๋ชจ๋‹ˆํ„ฐ๋ง")
print("- ๋งค์ผ 09:00: ์ผ์ผ ์‹œ์Šคํ…œ ๋ณด๊ณ ์„œ")

# ์ฆ‰์‹œ ํ•œ ๋ฒˆ ์‹คํ–‰
monitor_system()

while True:
schedule.run_pending()
time.sleep(60)

5. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ •๋ฆฌ ์ž‘์—…โ€‹

import schedule
import time
from datetime import datetime, timedelta
import sqlite3

def cleanup_old_logs():
"""์˜ค๋ž˜๋œ ๋กœ๊ทธ ๋ฐ์ดํ„ฐ ์‚ญ์ œ"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ •๋ฆฌ ์‹œ์ž‘...")

# 30์ผ ์ด์ƒ ๋œ ๋ฐ์ดํ„ฐ ์‚ญ์ œ
cutoff_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')

try:
conn = sqlite3.connect('app.db')
cursor = conn.cursor()

# ์˜ค๋ž˜๋œ ๋กœ๊ทธ ์‚ญ์ œ
cursor.execute("""
DELETE FROM logs
WHERE created_at < ?
""", (cutoff_date,))

deleted_count = cursor.rowcount

# ์˜ค๋ž˜๋œ ์„ธ์…˜ ์‚ญ์ œ
cursor.execute("""
DELETE FROM sessions
WHERE last_activity < ?
""", (cutoff_date,))

deleted_count += cursor.rowcount

conn.commit()
conn.close()

print(f"์ •๋ฆฌ ์™„๋ฃŒ: {deleted_count}๊ฐœ ๋ ˆ์ฝ”๋“œ ์‚ญ์ œ")

# ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ตœ์ ํ™”
optimize_database()

except Exception as e:
print(f"์ •๋ฆฌ ์‹คํŒจ: {e}")

def optimize_database():
"""๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ตœ์ ํ™”"""

print("๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ตœ์ ํ™” ์ค‘...")

try:
conn = sqlite3.connect('app.db')
conn.execute("VACUUM")
conn.close()

print("์ตœ์ ํ™” ์™„๋ฃŒ")

except Exception as e:
print(f"์ตœ์ ํ™” ์‹คํŒจ: {e}")

def backup_database():
"""๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ฐฑ์—…"""

print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ฐฑ์—… ์ค‘...")

import shutil
import os

source = 'app.db'
backup_dir = 'backups'
os.makedirs(backup_dir, exist_ok=True)

timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
destination = os.path.join(backup_dir, f'app_backup_{timestamp}.db')

try:
shutil.copy2(source, destination)

# ํŒŒ์ผ ํฌ๊ธฐ ํ™•์ธ
size_mb = os.path.getsize(destination) / (1024 * 1024)
print(f"๋ฐฑ์—… ์™„๋ฃŒ: {destination} ({size_mb:.2f} MB)")

except Exception as e:
print(f"๋ฐฑ์—… ์‹คํŒจ: {e}")

# ๋งค์ผ ์ƒˆ๋ฒฝ 3์‹œ์— ์ •๋ฆฌ ์ž‘์—…
schedule.every().day.at("03:00").do(cleanup_old_logs)

# ๋งค์ผ ์ƒˆ๋ฒฝ 2์‹œ์— ๋ฐฑ์—…
schedule.every().day.at("02:00").do(backup_database)

# ๋งค์ฃผ ์ผ์š”์ผ ์ƒˆ๋ฒฝ 4์‹œ์— ์ตœ์ ํ™”
schedule.every().sunday.at("04:00").do(optimize_database)

print("๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๊ด€๋ฆฌ ์Šค์ผ€์ค„๋Ÿฌ ์‹œ์ž‘")
print("- ๋งค์ผ 02:00: ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ฐฑ์—…")
print("- ๋งค์ผ 03:00: ์˜ค๋ž˜๋œ ๋ฐ์ดํ„ฐ ์ •๋ฆฌ")
print("- ๋งค์ฃผ ์ผ์š”์ผ 04:00: ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ตœ์ ํ™”")

while True:
schedule.run_pending()
time.sleep(60)

๋ฐฑ๊ทธ๋ผ์šด๋“œ ์‹คํ–‰โ€‹

๋ฐ๋ชฌ ํ”„๋กœ์„ธ์Šค๋กœ ์‹คํ–‰โ€‹

import schedule
import time
import daemon
import lockfile

def my_task():
print(f"์ž‘์—… ์‹คํ–‰: {time.strftime('%Y-%m-%d %H:%M:%S')}")

def run_scheduler():
schedule.every(10).seconds.do(my_task)

while True:
schedule.run_pending()
time.sleep(1)

# ๋ฐ๋ชฌ์œผ๋กœ ์‹คํ–‰
with daemon.DaemonContext(
working_directory='/path/to/working/dir',
pidfile=lockfile.FileLock('/var/run/scheduler.pid')
):
run_scheduler()

systemd ์„œ๋น„์Šค (Linux)โ€‹

# /etc/systemd/system/scheduler.service

[Unit]
Description=Python Scheduler Service
After=network.target

[Service]
Type=simple
User=username
WorkingDirectory=/home/username/scheduler
ExecStart=/usr/bin/python3 /home/username/scheduler/scheduler.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
# ์„œ๋น„์Šค ๋“ฑ๋ก ๋ฐ ์‹คํ–‰
sudo systemctl daemon-reload
sudo systemctl enable scheduler.service
sudo systemctl start scheduler.service

# ์ƒํƒœ ํ™•์ธ
sudo systemctl status scheduler.service

# ๋กœ๊ทธ ํ™•์ธ
sudo journalctl -u scheduler.service -f

nohup์œผ๋กœ ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์‹คํ–‰โ€‹

# ๋ฐฑ๊ทธ๋ผ์šด๋“œ๋กœ ์‹คํ–‰ (๋กœ๊ทธ ์ €์žฅ)
nohup python3 scheduler.py > scheduler.log 2>&1 &

# ํ”„๋กœ์„ธ์Šค ํ™•์ธ
ps aux | grep scheduler.py

# ํ”„๋กœ์„ธ์Šค ์ข…๋ฃŒ
kill <PID>

cron๊ณผ์˜ ๋น„๊ตโ€‹

cron ์‚ฌ์šฉ๋ฒ•โ€‹

# crontab ํŽธ์ง‘
crontab -e

# ๋งค์ผ ์˜ค์ „ 2์‹œ์— ๋ฐฑ์—… ์Šคํฌ๋ฆฝํŠธ ์‹คํ–‰
0 2 * * * /usr/bin/python3 /path/to/backup.py

# ๋งค 5๋ถ„๋งˆ๋‹ค ์‹คํ–‰
*/5 * * * * /usr/bin/python3 /path/to/monitor.py

# ํ‰์ผ ์˜ค์ „ 9์‹œ์— ์‹คํ–‰
0 9 * * 1-5 /usr/bin/python3 /path/to/report.py

# crontab ๋ชฉ๋ก ๋ณด๊ธฐ
crontab -l

schedule vs cronโ€‹

schedule ์žฅ์ :

  • Python ์ฝ”๋“œ ๋‚ด์—์„œ ๋ชจ๋“  ๊ฒƒ์„ ๊ด€๋ฆฌ
  • ์กฐ๊ฑด๋ถ€ ์‹คํ–‰์ด ์‰ฌ์›€
  • ๋””๋ฒ„๊น…์ด ์‰ฌ์›€
  • ํฌ๋กœ์Šค ํ”Œ๋žซํผ

cron ์žฅ์ :

  • ์‹œ์Šคํ…œ ๋ ˆ๋ฒจ ๊ด€๋ฆฌ
  • ๋” ์•ˆ์ •์ 
  • ์žฌ์‹œ์ž‘ ํ›„์—๋„ ์ž๋™ ์‹คํ–‰
  • ๋ณ„๋„ ํ”„๋กœ์„ธ์Šค ๋ถˆํ•„์š”
# schedule: Python ์ฝ”๋“œ ๋‚ด์—์„œ ๊ด€๋ฆฌ
import schedule

def backup():
# ์กฐ๊ฑด๋ถ€ ์‹คํ–‰์ด ์‰ฌ์›€
if is_weekday() and not is_holiday():
perform_backup()

schedule.every().day.at("02:00").do(backup)

APScheduler (๊ณ ๊ธ‰)โ€‹

๋” ๊ฐ•๋ ฅํ•œ ์Šค์ผ€์ค„๋ง์ด ํ•„์š”ํ•˜๋‹ค๋ฉด APScheduler๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”.

์„ค์น˜โ€‹

pip install apscheduler

์‚ฌ์šฉ ์˜ˆ์ œโ€‹

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime
import time

def job():
print(f"์ž‘์—… ์‹คํ–‰: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

# ์Šค์ผ€์ค„๋Ÿฌ ์ƒ์„ฑ
scheduler = BackgroundScheduler()

# ์ธํ„ฐ๋ฒŒ ๊ธฐ๋ฐ˜ ์ž‘์—…
scheduler.add_job(job, 'interval', seconds=10)

# cron ์Šคํƒ€์ผ ์ž‘์—…
scheduler.add_job(
job,
CronTrigger(hour=9, minute=0),
id='morning_job'
)

# ํŠน์ • ๋‚ ์งœ/์‹œ๊ฐ„์— ํ•œ ๋ฒˆ ์‹คํ–‰
scheduler.add_job(
job,
'date',
run_date=datetime(2024, 12, 31, 23, 59, 59)
)

# ์Šค์ผ€์ค„๋Ÿฌ ์‹œ์ž‘
scheduler.start()

print("APScheduler ์‹œ์ž‘")

try:
# ๋ฉ”์ธ ์Šค๋ ˆ๋“œ ์œ ์ง€
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()

์ž์ฃผ ๋ฌป๋Š” ์งˆ๋ฌธโ€‹

Q1. schedule์ด ์ •ํ™•ํ•œ ์‹œ๊ฐ„์— ์‹คํ–‰๋˜์ง€ ์•Š์•„์š”.โ€‹

A: schedule์€ ์ •ํ™•ํ•œ ํƒ€์ด๋ฐ์„ ๋ณด์žฅํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋” ์ •ํ™•ํ•œ ์‹คํ–‰์ด ํ•„์š”ํ•˜๋ฉด APScheduler๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”.

# schedule: ๋Œ€๋žต์ ์ธ ์‹œ๊ฐ„
schedule.every().day.at("10:30").do(job)

# APScheduler: ๋” ์ •ํ™•ํ•œ ์‹œ๊ฐ„
from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()
scheduler.add_job(job, 'cron', hour=10, minute=30)
scheduler.start()

Q2. ์Šค์ผ€์ค„๋Ÿฌ๊ฐ€ ๋ฉˆ์ถฐ์žˆ๋Š” ๊ฒƒ ๊ฐ™์•„์š”.โ€‹

A: time.sleep()์ด ๋„ˆ๋ฌด ๊ธธ๊ฑฐ๋‚˜ ์ž‘์—…์ด ๋ธ”๋กœํ‚น๋˜๊ณ  ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

# ๋‚˜์œ ์˜ˆ
while True:
schedule.run_pending()
time.sleep(3600) # 1์‹œ๊ฐ„ ๋Œ€๊ธฐ - ๋„ˆ๋ฌด ๊น€!

# ์ข‹์€ ์˜ˆ
while True:
schedule.run_pending()
time.sleep(1) # 1์ดˆ๋งˆ๋‹ค ์ฒดํฌ

Q3. ์ž‘์—…์ด ์‹คํ–‰ ์ค‘์ผ ๋•Œ ๋‹ค์Œ ์Šค์ผ€์ค„์ด ๊ฒน์น˜๋ฉด ์–ด๋–ป๊ฒŒ ๋˜๋‚˜์š”?โ€‹

A: ๊ธฐ๋ณธ์ ์œผ๋กœ ์ด์ „ ์ž‘์—…์ด ๋๋‚˜๊ธฐ๋ฅผ ๊ธฐ๋‹ค๋ฆฝ๋‹ˆ๋‹ค. ๋ณ‘๋ ฌ ์‹คํ–‰์ด ํ•„์š”ํ•˜๋ฉด ์Šค๋ ˆ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”.

import threading

def threaded_job():
thread = threading.Thread(target=long_running_task)
thread.start()

schedule.every(5).minutes.do(threaded_job)

Q4. ์Šค์ผ€์ค„๋Ÿฌ๊ฐ€ ์‹คํ–‰ ์ค‘์ธ์ง€ ์–ด๋–ป๊ฒŒ ํ™•์ธํ•˜๋‚˜์š”?โ€‹

A: ๋กœ๊น…์„ ์ถ”๊ฐ€ํ•˜๊ณ  ์ƒํƒœ ํŒŒ์ผ์„ ์ƒ์„ฑํ•˜์„ธ์š”.

import schedule
import logging
from datetime import datetime

# ๋กœ๊น… ์„ค์ •
logging.basicConfig(
filename='scheduler.log',
level=logging.INFO,
format='%(asctime)s - %(message)s'
)

def job():
logging.info("์ž‘์—… ์‹คํ–‰")
print("์ž‘์—… ์‹คํ–‰")

# ์ƒํƒœ ํŒŒ์ผ ์—…๋ฐ์ดํŠธ
def update_status():
with open('scheduler.status', 'w') as f:
f.write(datetime.now().isoformat())

schedule.every(1).minutes.do(update_status)
schedule.every(5).minutes.do(job)

logging.info("์Šค์ผ€์ค„๋Ÿฌ ์‹œ์ž‘")
print("์Šค์ผ€์ค„๋Ÿฌ ์‹œ์ž‘")

while True:
schedule.run_pending()
time.sleep(1)

Q5. ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•ด๋„ ์Šค์ผ€์ค„๋Ÿฌ๊ฐ€ ๊ณ„์† ์‹คํ–‰๋˜๊ฒŒ ํ•˜๋ ค๋ฉด?โ€‹

A: try-except๋กœ ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜์„ธ์š”.

import schedule
import time
import traceback

def safe_job():
try:
# ์‹ค์ œ ์ž‘์—…
risky_operation()
except Exception as e:
print(f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")
traceback.print_exc()
# ์—๋Ÿฌ ์•Œ๋ฆผ ์ „์†ก
send_error_notification(str(e))

def risky_operation():
# ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ์ž‘์—…
pass

def send_error_notification(error_msg):
# ์—๋Ÿฌ ์•Œ๋ฆผ (์ด๋ฉ”์ผ, Slack ๋“ฑ)
pass

schedule.every(10).minutes.do(safe_job)

while True:
try:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
print("\n์Šค์ผ€์ค„๋Ÿฌ ์ข…๋ฃŒ")
break
except Exception as e:
print(f"์Šค์ผ€์ค„๋Ÿฌ ์˜ค๋ฅ˜: {e}")
time.sleep(5) # ์ž ์‹œ ๋Œ€๊ธฐ ํ›„ ์žฌ์‹œ์ž‘

๋งˆ์น˜๋ฉฐโ€‹

์ถ•ํ•˜ํ•ฉ๋‹ˆ๋‹ค! Python ํ•™์Šต ์—ฌ์ •์„ ์™„์ฃผํ•˜์…จ์Šต๋‹ˆ๋‹ค.

์ง€๊ธˆ๊นŒ์ง€ ๋ฐฐ์šด ๋‚ด์šฉ:

  • Python ๊ธฐ์ดˆ: ๋ณ€์ˆ˜, ์ž๋ฃŒํ˜•, ์ œ์–ด๋ฌธ, ํ•จ์ˆ˜
  • ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ: ํด๋ž˜์Šค, ์ƒ์†, ๋ชจ๋“ˆ
  • ํŒŒ์ผ ๋ฐ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ: ํŒŒ์ผ ์ž…์ถœ๋ ฅ, ์—๋Ÿฌ ์ฒ˜๋ฆฌ
  • ์ž๋™ํ™”: ํŒŒ์ผ, ์—‘์…€, ์›น, ์Šค์ผ€์ค„๋ง

์ด์ œ ์—ฌ๋Ÿฌ๋ถ„์€:

  • ๋ฐ˜๋ณต์ ์ธ ์—…๋ฌด๋ฅผ ์ž๋™ํ™”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
  • ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์ง‘ํ•˜๊ณ  ๋ถ„์„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
  • ์‹ค์šฉ์ ์ธ ํ”„๋กœ๊ทธ๋žจ์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
  • ๋ฌธ์ œ๋ฅผ ์ฝ”๋“œ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค

๋‹ค์Œ ๋‹จ๊ณ„โ€‹

Python ํ•™์Šต์„ ๊ณ„์†ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด:

  1. ์›น ๊ฐœ๋ฐœ: Flask, Django๋กœ ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋งŒ๋“ค๊ธฐ
  2. ๋ฐ์ดํ„ฐ ๊ณผํ•™: pandas, numpy๋กœ ๋ฐ์ดํ„ฐ ๋ถ„์„ํ•˜๊ธฐ
  3. ๋จธ์‹ ๋Ÿฌ๋‹: scikit-learn, TensorFlow๋กœ AI ๋ชจ๋ธ ๋งŒ๋“ค๊ธฐ
  4. API ๊ฐœ๋ฐœ: FastAPI๋กœ REST API ์„œ๋ฒ„ ๊ตฌ์ถ•ํ•˜๊ธฐ
  5. GUI ํ”„๋กœ๊ทธ๋ž˜๋ฐ: tkinter, PyQt๋กœ ๋ฐ์Šคํฌํ†ฑ ์•ฑ ๋งŒ๋“ค๊ธฐ

๊ณ„์† ์„ฑ์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•โ€‹

  • ์‹ค์ „ ํ”„๋กœ์ ํŠธ: ๋ฐฐ์šด ๋‚ด์šฉ์„ ์‹ค์ œ ๋ฌธ์ œ์— ์ ์šฉํ•ด๋ณด์„ธ์š”
  • ์˜คํ”ˆ์†Œ์Šค ๊ธฐ์—ฌ: GitHub์—์„œ ํ”„๋กœ์ ํŠธ์— ์ฐธ์—ฌํ•ด๋ณด์„ธ์š”
  • ์ฝ”๋“œ ๋ฆฌ๋ทฐ: ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ๋ฅผ ์ฝ๊ณ  ๋ฐฐ์šฐ์„ธ์š”
  • ์ปค๋ฎค๋‹ˆํ‹ฐ ์ฐธ์—ฌ: Python ์ปค๋ฎค๋‹ˆํ‹ฐ์—์„œ ์งˆ๋ฌธํ•˜๊ณ  ๋‹ต๋ณ€ํ•˜์„ธ์š”

"๊ฐ€์žฅ ์ข‹์€ ํ•™์Šต ๋ฐฉ๋ฒ•์€ ๋งŒ๋“œ๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค."

์—ฌ๋Ÿฌ๋ถ„์˜ Python ์—ฌ์ •์ด ๊ณ„์†๋˜๊ธธ ์‘์›ํ•ฉ๋‹ˆ๋‹ค!